<template>
  <!--草稿箱详情 可查可改-->
  <div class="app-container">
    <el-form  ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="收件人" prop="receiverName">
        <el-input v-model="receiverName" 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="receiverAccount" v-show="false"/>
      </el-form-item>
      <el-form-item label="主题" prop="mailTheme">
        <el-input v-model="form.mailTheme" placeholder="请输入邮件主题" clearable />
      </el-form-item>
      <!--      :on-success="handleSuccess"-->
      <el-form-item label="附件">
        <el-upload
          class="upload-file"
          :before-upload="handleBefore"
          :before-remove="beforeRemove"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :show-file-list="true"
          :file-list="mail.oldFileList"
          :action=actionUp
          multiple
          :http-request="fileRequest"
        >
          <div slot="tip" class="el-upload__tip"></div>
          <el-button
            class="filter-item"
            type="primary"
            icon="el-icon-upload"
            size="mini"
          >上传</el-button>
        </el-upload>
        <ul v-show="!!mail.oldFileList.length" class="old-file-list"></ul>
      </el-form-item>
      <el-form-item label="邮件内容" prop="mailContent" style="height: 250px;">
        <Editor v-model="form.mailContent" />
      </el-form-item>
      <el-input v-model="status" v-show="false"/>
      <el-input v-model="fileName" v-show="false"/>
      <el-input v-model="filePath" v-show="false" />
      <el-form-item style="text-align:center;">
        <el-button type="primary" @click="submitForm">发 送</el-button>
        <el-button @click="submitForm1">保存草稿</el-button>
      </el-form-item>
    </el-form>

    <!-- 选择人员对话框 -->
    <select-user-by-dept ref="selectUserByDept" :title="title" :open="open" :inputName="receiverName" :inputAccount="receiverAccount" append-to-body @ok="selectOK"/>


  </div>
</template>

<script>

  import { listInfo, delInfo, addInfo, exportInfo,selectRen,treeselect as deptTreeselect ,uploadFujian} from "@/api/system/email/send";
  import {getInfo } from "@/api/system/email/info";
  import {updateInfo } from "@/api/system/email/info";
  import Editor from '@/components/Editor';
  import SelectUserByDept from "@/components/SelectRen/selectUserByDept";


  export default {
    name: 'draftinfo',
    components: {
      Editor,
      SelectUserByDept
    },
    data() {
      return {
        userIds: '',
        // 选中数组
        ids: [],
        // 遮罩层
        loading: true,
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          mailTheme: [
            { required: true, message: "主题不能为空", trigger: "blur" }
          ]
        },
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        options1: "",
        deptOptions: undefined,
        receiverName: "", // 收件人的昵称
        receiverAccount: "", // 收件人的账号
        filterText: '',  //人员选择器中的 筛选
        mail: {
          oldFileList: [],
          fileList: []
        },
        actionUp:'aaaa',//接口地址
        fujianName:'',
        fujianPath:'',
        status:'',
        mailGuid:this.$route.query.id
      };
    },
    created() {
      //this.getList();
      // this.getDeptTreeselect();
      this.info();
    },
    // activated: function() {
    //   this.info();
    // },
    methods: {
      info(row){
        console.log(this.$route.query.id);
        const mailGuid = this.$route.query.id
        getInfo(mailGuid).then(response => {
          this.form = response.data;
          // console.log(response.data);
         this.receiverName = response.data.receiverName;
         // this.form.mailContent = response.data.mailContent;
         this.receiverAccount = response.data.receiverAccount;
         this.filterText = response.data.receiverName;
         this.status = response.data.status;

         // this.fujianName = response.data.fileName + ',';
         // console.log(this.fujianName);
         // this.fujianPath = response.data.filePath + ',';
         // console.log(this.fujianPath);

          this.fujianPath =response.data.filePath;
          this.fujianName =response.data.fileName;
          if(this.fujianPath!="")
            this.fujianPath+= ",";
          if(this.fujianName!="")
            this.fujianName+= ",";
          let fujianPathArr =response.data.filePath .split(',')
          let fujianNameArr =response.data.fileName .split(',')
          // console.log(this.fujianName);
          // console.log(this.fujianPath);
          for(var i=0;i< fujianNameArr.length;i++){
            this.mail.oldFileList.push({
              "name":fujianNameArr[i],
              "url": process.env.VUE_APP_BASE_API + fujianPathArr[i],
            });
          };

        });
      },
      // 人员选择器----取消按钮
      cancel() {
        this.open = false;
        this.filterText='';
      },
      // 表单重置
      reset() {
        this.form = {
          mailGuid: undefined,
          receiverName: undefined,
          receiverAccount: undefined,
          mailTheme: undefined,
          mailContent: undefined,
          status: "0",
        };
        this.receiverName='';
        this.receiverAccount='';
        this.fujianName='';
        this.fujianPath='';
        this.mail.oldFileList=[];
        this.mail.fileList=[];
        this.resetForm("form");
      },
      /** 写信==发送、保存草稿*/
      submitForm: function() {

        this.form.receiverAccount = this.receiverAccount;
        this.form.receiverName = this.receiverName;
        if(this.fujianName!='' && this.fujianPath!=''){
          this.form.fileName = this.fujianName.substring(0, this.fujianName.length - 1);
          this.form.filePath = this.fujianPath.substring(0, this.fujianPath.length - 1);
        }

        // this.form.status = status;
        this.form.status = '1';
        updateInfo(this.form).then(response => {
          if (response.code === 200) {
            this.msgSuccess("发送成功");
            this.reset();
          }
        });
      },
      submitForm1: function(status) {

        // this.form.receiverAccount = this.receiverAccount;
        // this.form.receiverName = this.receiverName;
        console.log(this.fujianName+"=="+this.fujianPath);
        if(this.fujianName!='' && this.fujianPath!=''){
          this.form.fileName = this.fujianName.substring(0, this.fujianName.length - 1);
          this.form.filePath = this.fujianPath.substring(0, this.fujianPath.length - 1);
        }

        // this.form.status = status;
        this.status = '0';
        updateInfo(this.form).then(response => {
          if (response.code === 200) {
            this.msgSuccess("保存成功");
          }
        });
      },
      /** 加载修改树结构json */
      findZNodes: function () {
        selectRen(this.queryParams).then(response => {
          this.options1 = response.data;
        });
      },
      /** 查询部门树结构 */
      getDeptTreeselect() {
        deptTreeselect().then(response => {
          this.deptOptions = response.data;
        });
      },
      /** 写信中的 选择人员 按钮弹窗操作 */
      handleSelect() {
        this.open = true;
        this.title = "选择收件人";
      },
      /** 人员选择器中的 选定按钮操作 */
      submitRen(){
        this.receiverName =this.$refs.renlist.names.join(',');
        this.receiverAccount=this.$refs.renlist.accounts.join(',');
        this.open = false;
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      /** 附件上传---开始  */
      handleBefore(file) {
        // 上传前可以对要上传文件进行控制
        // if (file.type.indexOf("image/") == -1) {
        //   this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
        // }
      },
      // handleSuccess(file, fileInfo) {
      //   console.log(fileInfo);
      //   this.mail.fileList.push({
      //     name: fileInfo.name,
      //     uuid: fileInfo.uid,
      //     url: fileInfo.url
      //   });
      // },
      handlePreview(file) {
        // 预览,一些文件因为格式问题无法预览。推荐使用a标签，src为文件的下载地址，点击即可下载,参照录音
        window.open(file.url);
      },
      handleRemove(file) {
        // 移除
        this.mail.oldFileList.forEach((item, index) => {
          if (item.uid === file.uid) {
            //删除
            this.mail.oldFileList.splice(index, 1)
            let fujianNameArr = this.fujianName.split(',');
            let fujianPathArr = this.fujianPath.split(',');
            //重名
            for (var i = 0; i < fujianPathArr.length; i++) {
              if (process.env.VUE_APP_BASE_API + fujianPathArr[i] == file.url) {
                //放一起的目的是 解决重名引起的 账号和名称不对应 问题
                fujianNameArr.splice(i, 1);
                fujianPathArr.splice(i, 1);
                break;
              }
            }
            this.fujianName = fujianNameArr.join(',');
            this.fujianPath = fujianPathArr.join(',');
          }
        });
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      fileRequest(item) {
        let uploadData = new FormData()
        uploadData.append('file',item.file)
        uploadFujian(uploadData).then(response => {
          if (response.code === 200) {
            this.fujianName += response.fileName + ',';
            this.fujianPath += response.url + ',';
            this.mail.oldFileList.push({
              name: response.fileName,
              url: process.env.VUE_APP_BASE_API + response.url
            });
            console.log(process.env.VUE_APP_BASE_API + response.url);
            this.msgSuccess("上传成功");
          }
        });
      }
    },

    /** 选择人员 按钮弹窗操作 */
    handleSelect() {
      this.$refs.selectUserByDept.childOpen=true;
      this.open = true;
      this.title = "选择收件人";
    },
    /** 人员选择器的返回值  */
    selectOK(zh, xm) {
      this.receiverAccount = zh;
      this.receiverName=xm;
      this.open=false;
    },

    watch: {
      /** 人员选择器中的 筛选 */
      filterText(val) {
        this.$refs.tree.filter(val);
      },

      $route(n,o){
        if(n.fullPath !== o.fullPath){ //监听路由参数是否变化
          this.mail.oldFileList = [];
          this.info()  //methods中封装的加载数据函数
        }
      },

      // 监听相同路由下参数变化的时候，从而实现异步刷新
      // '$route':function(newUrl,oldUrl){
      //   this.mailGuid=this.$route.query.id;
      // },
      // mailGuid: function() {
      //   this.info()
      // }
    }

  }
</script>

<style lang="less" scoped>
  .el-input-group__append, .el-input-group__prepend{
    background: #188efd !important;
    color: #fff !important;
  }
</style>
