<template>
  <div class="app-container">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px"
        label-position="left">
        <el-row>
        <el-col :span="24">
          <el-form-item label="收件主体" prop="deptflg" >
            <el-radio-group v-model="formData.deptflg" size="medium" @change="agreeChange">
              <el-radio v-for="(item, index) in deptflgOptions" :key="index" :label="item.value"
                        :disabled="item.disabled">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="24" v-if="showsjr">
          <el-form-item label="收件人" prop="RecvPerson">
            <el-input v-model="formData.RecvPerson" placeholder="请选择收件人" clearable="true">
              <template slot="append">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleSelect">
                  选择人员
                </el-button>
              </template>
            </el-input>
            <el-input v-model="formData.RecvAccount" v-show="false"/>
          </el-form-item>
        </el-col>

        <!--        <el-col :span="24">-->
        <!--          <el-form-item label="收件单位" prop="deptId">-->
        <!--            <treeselect v-model="formData.deptId" :options="deptOptions" :disable-branch-nodes="true" :show-count="true" placeholder="请选择收件单位" show-checkbox/>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->

        <el-col :span="24" v-if="showdw">
          <el-form-item label="收件单位" prop="deptId">
            <el-tree
              :data="deptOptions"
              show-checkbox
              default-expand-all
              ref="dept"
              node-key="id"
              empty-text="加载中，请稍后"
              :props="defaultProps"
            ></el-tree>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="通知标题" prop="Title">
            <el-input v-model="formData.Title" placeholder="请输入通知标题" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="通知内容" prop="Content" style="height: 240px;">
            <Editor v-model="formData.Content" />
<!--            <el-input v-model="formData.Content" type="textarea" placeholder="请输入通知内容"-->
<!--              :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>-->
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="附件上传" prop="fj">
            <el-upload action="#"
                       :before-upload="fjBeforeUpload"
                       :on-remove="handleRemove"
                       :on-preview="handlePreview"
                       :before-remove="beforeRemove"
                       :show-file-list="true"
                       :file-list="fjfileList"
                       :http-request="fileRequest">
              <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
            </el-upload>
            <ul v-show="!!fjfileList.length" ></ul>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="联系人" prop="ContactPerson">
            <el-input v-model="formData.ContactPerson" placeholder="请输入联系人" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="ContactTel">
            <el-input v-model="formData.ContactTel" placeholder="请输入联系电话" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" style="text-align:center">
          <el-form-item size="large">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
        </el-row>
      </el-form>


    <!-- 选择人员对话框 -->
    <el-dialog :title="tctitle" :visible.sync="open" width="1000px" append-to-body>
      <SelectRen ref="renlist"/>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitRen">选 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

  import SelectRen from '@/components/SelectRen';
  import { addtzfs,uploadfj } from "@/api/system/tzgl/tzfs";
  import { treeselect } from "@/api/system/dept";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import Editor from '@/components/Editor';
export default {
  components: {
    SelectRen,
    Treeselect,
    Editor,
  },
  props: [],
  data() {
    return {
      formData: {
        Title: '',
        Content: '',
        ContactPerson: '',
        ContactTel: '',
        RecvAccount:'',
        RecvPerson:'',
        deptId:'',
        deptflg:0,
        fileName:'',
        filePath:'',
      },

      rules: {
        deptId:[{
          required:true,
          message:'请选择收件单位',
          trigger:'blur'
        }],
        RecvPerson:[{
          required:true,
          message:'请选择收件人',
          trigger:'blur'
        }],
        deptflg:[{
          required:true,
          message:'请选择收件主体',
          trigger:'blur'
        }],
        Title: [{
          required: true,
          message: '请输入通知标题',
          trigger: 'blur'
        }],
        Content: [{
          required: true,
          message: '请输入通知内容',
          trigger: 'blur'
        }],
        SendPerson: [{
          required: true,
          message: '请输入收件人',
          trigger: 'blur'
        }],
        SendAccount: [{
          required: true,
          message: '请输入收件单位',
          trigger: 'blur'
        }],
        ContactPerson: [{
          required: true,
          message: '请输入联系人',
          trigger: 'blur'
        }],
        ContactTel: [{
          required: true,
          message: '请输入联系电话',
          trigger: 'blur'
        }],
      },
      fjfileList: [],
      fileList:[],

      // 弹出层标题
      tctitle: "",
      // 是否显示弹出层
      open: false,
      filterText: '',  //人员选择器中的 筛选
      // 部门树选项
      deptOptions: [],
      defaultProps: {
        children: "children",
        label: "label"
      },

      // 部门id
      depid: [],
      deptflgOptions: [{
        "label": "个人",
        "value": 0
      }, {
        "label": "单位",
        "value": 1
      }],

      showsjr:true,
      showdw:false,
    }
  },
  // computed: {},
  // watch: {},
  created() {
    this.getTreeselect();
  },
  //mounted() {},
  methods: {
    submitForm() {
      this.$refs['elForm'].validate(valid => {
        // TODO 提交表单
        if (this.formData.deptflg === 1) {
          this.formData.deptId = "";
          this.depid = this.getDeptAllCheckedKeys();
          if (this.depid.length > 0) {
            for (let i = 0; i < this.depid.length; i++) {
              this.formData.deptId += this.depid[i] + ',';
            }
          }
        }

        addtzfs(this.formData).then(response => {
         // debugger;
          if (response.code === 200) {
            this.msgSuccess("发送成功");
            this.open = false;
            this.reset();
          }
        });
      })
    },

    // 表单重置
    reset() {
      this.formData = {
        Title: '',
        Content: '',
        ContactPerson: '',
        ContactTel: '',
        RecvAccount: '',
        RecvPerson: '',
        deptId: '',
        deptflg: 0,
        fileName: '',
        filePath: '',
      };

      this.showsjr = true;
      this.showdw = false;
      this.depid = [];
      this.deptOptions = [];
      this.open = false;
      this.fjfileList = [];
      this.fileList = [];
      this.resetForm();
    },

    resetForm() {
      this.$refs['elForm'].resetFields()
    },

    /** ---------------收件人---------------*/
    handleSelect() {
      this.open = true;
      this.tctitle = "选择收件人";
    },
    submitRen(){
      this.formData.RecvPerson =this.$refs.renlist.names.join(',');
      this.formData.RecvAccount=this.$refs.renlist.accounts.join(',');
      this.open = false;
    },
    watch: {
      /** 人员选择器中的 筛选 */
      filterText(val) {
        this.$refs.tree.filter(val);
      }
    },
    /** ---------------收件人end---------------*/
    cancel() {
      this.open = false;
      this.filterText='';
    },
    /** --------------查询部门下拉树结构---------------- */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      //debugger;
      this.queryParams.deptId = data.id;
    },
    /** 根据角色ID查询部门树结构 */
    getRoleDeptTreeselect(roleId) {
      roleDeptTreeselect(roleId).then(response => {
        this.deptOptions = response.depts;
        this.$refs.dept.setCheckedKeys(response.checkedKeys);
      });
    },
    /** 查询部门树结构 */
    getDeptTreeselect() {
      deptTreeselect().then(response => {
        this.deptOptions = response.data;
      });
    },

    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getHalfCheckedKeys();
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      //return checkedKeys;
      return halfCheckedKeys;
    },
    /** 根据角色ID查询部门树结构 */
    getRoleDeptTreeselect(roleId) {
      roleDeptTreeselect(roleId).then(response => {
        this.deptOptions = response.depts;
        this.$refs.dept.setCheckedKeys(response.checkedKeys);
      });
    },
    /** ---------------查询部门下拉树结构end----------------- */

    /** ---------------附件----------------- */
    fjBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      return isRightSize
    },
    handlePreview(file) {
      // 预览,一些文件因为格式问题无法预览。推荐使用a标签，src为文件的下载地址，点击即可下载,参照录音
      window.open(file.filePath);
    },
    handleSuccess(file, fileInfo) {
      console.log(fileInfo);
      //debugger;
      this.fileList.push({
        name: fileInfo.name,
        uuid: fileInfo.uid,
        filePath: fileInfo.url
      });
    },
    handleRemove(file) {
      // 移除
      this.fjfileList.forEach((item, index) => {
       // debugger;
        console.log(item);
        if (item.uid === file.uid) {
          this.fjfileList.splice(index, 1);
          //删除
        }
      });
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    fileRequest(item) {
      let uploadData = new FormData()
      uploadData.append('file',item.file)
      uploadfj(uploadData).then(response => {
        if (response.code === 200) {
          this.formData.fileName += response.data.fileName+',';
          this.formData.filePath += response.data.filePath+',';
          this.fjfileList.push({
            name: response.data.fileName,
            filePath: process.env.VUE_APP_BASE_API+response.data.filePath
          });
          this.msgSuccess("上传成功");
        }
      }).catch(function(e) {
        console.log('catch:', e);})
    },
    /** ---------------附件end----------------- */
    agreeChange(val){
      let app = this;
      //debugger;
      this.formData.deptflg=val;
      if(val===0)
      {
        this.showsjr=true;
        this.showdw=false;
      }
      else if(val===1)
      {
        this.showsjr=false;
        this.showdw=true;
      }
    },
  }
};
</script>
<style >
.el-upload__tip {
  line-height: 1.2;
}
.el-input-group__append, .el-input-group__prepend{
  background: #188efd !important;
  color: #fff !important;
}
</style>
