<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":disabled="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" v-if="showdw">
          <el-form-item label="收件单位" prop="deptId">
            <el-input v-model="formData.RecvPerson" placeholder="请选择单位" clearable="true":disabled="true">
              <template slot="append">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  size="mini"
                  @click="handledept">
                  选择单位
                </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="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>
    <el-dialog :title="tctitle" :visible.sync="open1" width="20%" append-to-body style="size: 30px">
      <el-tree
        :data="deptOptions"
        show-checkbox
        default-expand-all
        ref="dept"
        node-key="id"
        empty-text="加载中，请稍后"
        :props="defaultProps"
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="getDeptAllCheckedKeys">确 定</el-button>
        <el-button @click="cancel">取 消</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,
        open1:false,
        filterText: '',  //人员选择器中的 筛选

        // 部门树选项
        deptOptions: [],
        defaultProps: {
          children: "children",
          label: "label"
        },

        // 部门id
        depid:[],
        depname:[],
        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 提交表单
          console.log( this.formData.RecvAccount)
          console.log("this.deptid")
          if (this.formData.deptflg === 1) {
            this.formData.deptId = "";
           // this.depid = this.getDeptAllCheckedKeys();
            this.depid = this.formData.RecvAccount;
            if (this.depid.length > 0) {
              for (let i = 0; i < this.depid.length; i++) {
                if (this.depid!=100&&this.depid!=101){
                  this.formData.deptId += this.depid[i] + ',';
                }
              }
            }
          }
          addtzfs(this.formData).then(response => {
            if (response.code === 200) {
              this.msgSuccess("发送成功");
              this.open = false;
              this.open1 = false;
              this.getTreeselect();
              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.open1 = false;
        this.fjfileList = [];
        this.fileList = [];
        this.depname=[];
        this.resetForm();
      },
      resetForm() {

        this.depname=[];
        this.formData.RecvPerson=[];
        this.formData.RecvAccount=[];
        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.open1 = false;
        this.filterText='';

      },
      handledept() {
        this.open1 = true;
        this.tctitle = "选择部门";
      },
      /** --------------查询部门下拉树结构---------------- */
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data;
          var a=this.deptOptions;
          for (let i = 0; i <a.length ; i++) {
            console.log( this.deptOptions[i].children[0].id)
            console.log(a[i].id)
          }

        });
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        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();
        let a= this.$refs.dept.getCheckedNodes();
        var q=this.deptOptions;
        let e="";
        for (let w = 0; w <q.length ; w++) {
          e += q[w].children[w].id
        }
        for (let i = 0; i <a.length ; i++) {
          if (a[i].id!=100&&a[i].id!=e){
            this.depname.push(a[i].label)
            this.depid.push(a[i].id)
          }
        }
        console.log(a)
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        this.formData.RecvAccount =this.depid;
        this.formData.RecvPerson = this.depname ;
        this.open1=false;
        this.depname=[];
        this.depid=[];
        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 < 50

        if (!isRightSize) {
          this.$message.error('文件大小超过 50MB')
        }
        return isRightSize
      },
      handlePreview(file) {
        // 预览,一些文件因为格式问题无法预览。推荐使用a标签，src为文件的下载地址，点击即可下载,参照录音
        window.open(file.filePath);
      },
      handleSuccess(file, fileInfo) {
        console.log(fileInfo);

        this.fileList.push({
          name: fileInfo.name,
          uuid: fileInfo.uid,
          filePath: fileInfo.url
        });
      },
      handleRemove(file) {
        // 移除
        this.fjfileList.forEach((item, index) => {

          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;

        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>
