<template>
  <div>
    <div class="simple-container">
      <simple-form :form="table_form" :reset="true" @search="handleSearch">
      </simple-form>
      <el-button
        style="float: right; margin-bottom: 20px"
        type="primary"
        @click="dialogCheck()"
        >添加</el-button
      >
      <simple-table
        :list="table_list"
        :config="table_config"
        :handle-row="table_handle_row"
        @detail="handleDetail"
        @issue="handReply"
        @redit="handleEdit"
        @delete="handleDelete"
      ></simple-table>
    </div>
    <el-dialog
      :title="titleName"
      :visible.sync="dialogStatus"
      width="50%"
      :before-close="beforeClose"
      :destroy-on-close="true"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :fullscreen="true"
    >
      <div>
        <el-form
          :model="infolist"
          class="demo-ruleForm"
          ref="infolist"
          :rules="rules"
          style="height: calc(100vh - 180px); overflow-y: scroll"
        >
          <div class="info-line">
            <el-form-item prop="orderType">
              <span>类型</span>
              <el-select
                v-model="infolist.orderType"
                @change="selectClick"
                placeholder="类型选择"
                :disabled="DisableStatusb"
              >
                <el-option label="收集" value="0"></el-option>
                <el-option label="分享" value="1"></el-option>
              </el-select>
              <!--                <span>{{leimsg}}</span>-->
            </el-form-item>

            <el-form-item prop="orderName">
              <span>名称</span>
              <el-input
                v-model="infolist.orderName"
                placeholder="工单名称"
                :disabled="disableStatus"
              >
              </el-input>
              <!--                <span>{{namemsg}}</span>-->
            </el-form-item>
            <el-form-item prop="issuedTime">
              <span>截止日期</span>
              <el-date-picker
                :disabled="disableStatus"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                v-model="infolist.issuedTime"
                type="date"
              >
              </el-date-picker>
              <!--                <span>{{rmsg}}</span>-->
            </el-form-item>
            <el-form-item class="info-line online" prop="receiverList">
              <span>接收人</span>
              <!-- <deptTree
                v-if="!disableStatus"
                :closeList="closeList"
                class="tree"
                @treeCheck="treeCheck"
              >
              </deptTree> -->
              <deptTree
                :closeList="closeList"
                class="tree"
                @treeCheck="treeCheck"
              ></deptTree>
              <div
                v-if="DisableStatus"
                :class="!disableStatus ? 'tree treeUser' : 'tree treeUserb'"
              >
                <p v-for="(item, index) in treeList" :key="index">
                  {{ item.toUserId }}
                  <i @click="deletes(item, index)" class="el-icon-error"></i>
                </p>
              </div>
              <!--                <span>{{peomsg}}</span>-->
            </el-form-item>
            <el-form-item prop="approvalType" ref="approvalType">
              <span>审批规则</span>
              <el-select
                v-model="infolist.approvalType"
                placeholder="审批规则"
                :disabled="showStatus"
              >
                <el-option label="无需审批" value="0"></el-option>
                <el-option label="需抄送领导" value="1"></el-option>
                <el-option label="需领导审批" value="2"></el-option>
              </el-select>
              <!--                <span>{{shenmsg}}</span>-->
            </el-form-item>
            <el-form-item>
              <span>材料说明</span>
              <el-input
                v-model="infolist.material"
                placeholder="材料说明"
                :disabled="disableStatus"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="mkFileShareAttachList">
              <span>附件材料</span>
              <el-upload
                class="upload-demo"
                drag
                action="fakeaction"
                :http-request="upLoad"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :file-list="fileList"
                :before-remove="beforeRemove"
                multiple
              >
                <i class="el-icon-upload"></i>
                <div style="width: 100%" class="el-upload__text">
                  点击上传附件
                </div>
              </el-upload>
              <!--                <span>{{fujianmsg}}</span>-->
            </el-form-item>
            <div v-if="detailStatus" style="width: 100%">
              <div class="detail-title">修改记录</div>
              <simple-table
                :list="detail_list"
                :config="detail_config"
              ></simple-table>
            </div>
          </div>
          <div class="dialog-footer myfooter" style="text-align: center">
            <el-button
              type="primary"
              class="footer-button"
              @click="dialogCli(3, row_id)"
              >确 定</el-button
            >
            <el-button @click="dialogCli(2)" class="footer-button"
              >取 消</el-button
            >
          </div>
        </el-form>
      </div>
    </el-dialog>
    <el-dialog
      title="下载情况"
      :visible.sync="reditStatus"
      width="50%"
      :destroy-on-close="true"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :fullscreen="true"
    >
      <simple-table
        :list="download_list"
        :config="download_config"
      ></simple-table>
    </el-dialog>
    <el-dialog
      title="回复情况"
      :visible.sync="repltStatus"
      width="50%"
      :destroy-on-close="true"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :fullscreen="true"
    >
      <simple-table
        :list="replt_list"
        :config="replt_config"
        :handle-row="replt_handle_row"
        @state="handleDown"
        @goout="outClick"
      ></simple-table>
    </el-dialog>
  </div>
</template>

<script>
import simpleForm from "./components/form.vue";
import simpleTable from "./components/table.vue";
import deptTree from "../../../components/deptTreeUser.vue";
export default {
  components: {
    deptTree,
    simpleForm,
    simpleTable,
  },
  data() {
    // if(this.infolist.orderType === '1'){
    //     this.$refs.guize.clearValidate()
    // }
    return {
      titleName: "", //修改 新增表头
      DisableStatus: false,
      DisableStatusb: false,
      fileList: [],
      rules: {
        orderType: [
          { required: true, message: "请选择工单类型", trigger: "change" },
        ],
        orderName: [
          { required: true, message: "请输入工单名称", trigger: "blur" },
        ],
        issuedTime: [
          { required: true, message: "请选择截止日期", trigger: "change" },
        ],
        receiverList: [
          { required: true, message: "请选择接收人", trigger: "change" },
        ],
        approvalType: [
          { required: true, message: "请选择审批规则", trigger: "change" },
        ],
        mkFileShareAttachList: [
          { required: true, message: "请上传附件材料", trigger: "change" },
        ],
      },
      //   leimsg:"",
      //   fujianmsg:"",
      //   rmsg:"",
      //   namemsg:"",
      // shenmsg:"",
      // peomsg:"",
      showStatus: false, //收集时显示
      disableStatus: false, //树形图
      detailStatus: false, //修改人底部弹窗
      reditStatus: false, //下载情况弹窗
      repltStatus: false, //回复情况弹窗
      treeList: [], //负责人列表
      a: [], //负责人列表
      closeList: [],
      infolist: {},
      dialogStatus: false,
      table_search: {},
      table_form: [
        {
          label: "名称",
          props: "orderName",
          type: "input",
        },
        {
          label: "截止时间",
          props: "issuedTime",
          type: "datetime",
        },
        {
          label: "类型",
          props: "orderType",
          type: "select",
          dictionary: [
            {
              label: "收集",
              value: "0",
            },
            {
              label: "分享",
              value: "1",
            },
          ],
        },
      ],
      //  表头配置
      table_config: [
        {
          label: "名称",
          props: "orderName",
        },
        {
          label: "类型",
          props: "orderType",
        },
        {
          label: "截止时间",
          props: "issuedTime",
          // type: "time",
        },
        {
          label: "发起人",
          props: "createId",
        },
        {
          label: "下发时间",
          props: "createTime",
        },
      ],
      detail_config: [
        {
          label: "序号",
          props: "id",
        },
        {
          label: "修改时间",
          props: "updateTime",
        },
        {
          label: "修改人",
          props: "updatePerson",
          // type: "time",
        },
        {
          label: "修改内容",
          props: "updateContent",
        },
        // {
        //   label: "下发时间",
        //   props: "createTime",
        // },
      ],
      //修改记录
      detail_list: [],
      download_config: [
        {
          label: "序号",
          props: "id",
        },
        {
          label: "单位",
          props: "groupName",
        },
        {
          label: "下载记录",
          props: "opName",
          // type: "time",
        },
      ],
      replt_config: [
        {
          label: "序号",
          props: "ids",
        },
        {
          label: "回复单位",
          props: "groupName",
        },
        {
          label: "回复情况",
          props: "procedure",
        },
        {
          label: "回复内容",

          props: "state",
          type: "click",
        },
      ],
      replt_list: [
        {
          templateName: "1",
        },
      ],
      download_list: [],
      //   表格里的操作按钮delete
      table_handle_row: [
        {
          label: "回复情况",
          props: "issue",
          visible: {
            status: ["0"],
          },
        },
        {
          label: "下载情况",
          props: "redit",
          visible: {
            status: ["1"],
          },
        },
        {
          label: "修改",
          props: "detail",
        },
        {
          label: "撤销",
          props: "delete",
          //   visible: {
          //     status: ["0", "2"],
          //   },
          popconfirm: true,
        },
      ],
      replt_handle_row: [
        {
          label: "退回",
          props: "goout",
          visible: {
            status: ["0"],
          },
        },
      ],
      table_list: [],
      row_id: "",
    };
  },
  created() {
    let data = {
      page: "1",
      pageSize: "10",
    };
    this.handleInit(data);
  },

  methods: {
      beforeRemove(file){
          this.infolist.mkFileShareAttachList = []
      },
    selectClick(e) {
      if (e == 1) {
        this.showStatus = true;
        this.$refs.approvalType.clearValidate();
      } else {
        this.showStatus = false;
      }
    },
    beforeClose() {
      this.dialogStatus = false;
      this.infolist = {};
    },
    //点击下载回调
    handleDown(e) {
      if (e.subAttach.trim() === '' || e.subAttach === null) {
        this.$message.error("未回复暂无文件下载");
      } else {
        if (e.mkFileShareAttachList.length > 1) {
          this.moreDown(e.mkFileShareAttachList);
        } else {
          this.download(e.mkFileShareAttachList[0]);
        }
      }
    },
    //单文件下载方法
    async download(fileData) {
      await this.$http({
        url: "/market/cmkFileShare/downFile",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        responseType: "blob",
        data: { id: fileData.fileCode, fileName: fileData.fileName },
      }).then((response) => {
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          let blob = new Blob([response.data], {
            type: "application/vnd.ms-excel",
          });
          window.navigator.msSaveOrOpenBlob(blob, fileData.fileName);
        } else {
          /* 火狐谷歌的文件下载方式 */
          var blob = new Blob([response.data]);
          var downloadElement = document.createElement("a");
          var href = window.URL.createObjectURL(blob);
          downloadElement.href = href;
          downloadElement.download = fileData.fileName;
          document.body.appendChild(downloadElement);
          downloadElement.click();
          document.body.removeChild(downloadElement);
          window.URL.revokeObjectURL(href);
        }
      });
    },
    async moreDown(file) {
      let arr = [];
      file.forEach((item) => {
        arr.push({
          id: item.fileCode,
          fileName: item.fileName,
        });
      });
      await this.$http({
        url: "/market/cmkFileShare/downAllFile",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        responseType: "blob",
        data: { mkFileShareAttachList: arr },
      }).then((response) => {
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          let blob = new Blob([response.data], {
            type: "application/vnd.ms-excel",
          });
          window.navigator.msSaveOrOpenBlob(
            blob,
            new Date().getTime().toString() + ".zip"
          );
        } else {
          /* 火狐谷歌的文件下载方式 */
          var blob = new Blob([response.data]);
          var downloadElement = document.createElement("a");
          var href = window.URL.createObjectURL(blob);
          downloadElement.href = href;
          downloadElement.download = new Date().getTime().toString() + ".zip";
          document.body.appendChild(downloadElement);
          downloadElement.click();
          document.body.removeChild(downloadElement);
          window.URL.revokeObjectURL(href);
        }
      });
    },
    //获取树形组件返回值
    treeCheck(e) {
      let receiverList = [];
      e.map((item) => {
        let array = {
          toUserId: item.receiveNo,
        };
        receiverList.push(array);
      });
      this.$set(this.infolist, "receiverList", receiverList);
      this.$refs["infolist"].validateField("receiverList");
    },

    //时间处理方法
    // formatDate(str) {
    //     console.log(str)
    //     return str.replace(/(?<=\/|-|\.|:|\b|T)\d{1}(?=\/|-|\.|:|\b|T)/g, "0$&");
    // },
      async getReceiverList(){
          let a = window.sessionStorage.getItem('userInfo')
          if(this.infolist.receiverList){
              for(let i=0;i<=this.infolist.receiverList.length-1;i++){
                  if(this.infolist.receiverList[i].approvalId === JSON.parse(a).loginNo){
                      this.$message.error('不允许选择自己');
                      return false;
                  }
          }

          }
      },
    //底部按钮方法
    async dialogCli(id, row_id) {
      if (id == 2) {
        this.dialogStatus = false;
        this.detailStatus = false;
         return false;
      }
      let b = await this.getReceiverList()
        if(b!=false){

            const d = new Date();
            const month = d.getMonth()+1<10?'0'+(d.getMonth()+1):d.getMonth()+1;
            const date = d.getDate()<10 ?'0'+(d.getDate()+1):d.getDate()
            let dates = (
                d.getFullYear() + "-" + month+ "-" + date
            );
            console.log(dates)

            if (this.infolist.issuedTime < dates) {
                this.$message.error("请选择正确截止时间");
            } else {
                if (row_id) {
                    this.$set(this.infolist, "id", row_id);
                    //提交文件
                    this.$refs["infolist"].validate((valid) => {
                        this.infolist.treeList = JSON.parse(window.sessionStorage.getItem('treeList'))
                        if (valid) {
                            this.$http({
                                url: "/market/CMKFile/UptateCMKFileTemplateById",
                                method: "post",
                                headers: {
                                    "Content-Type": "application/json",
                                },
                                data: this.infolist,
                            }).then((res) => {
                                if (res.status == 200) {
                                    this.dialogStatus = false;
                                    this.row_id = "";
                                    this.infolist = {};
                                    this.detailStatus = false;
                                    this.handleInit({ page: "1", pageSize: "10" });
                                }
                            });
                        } else {
                            this.$message.error("请填写必填项");
                            return false;
                        }
                    });

                    //提交文件
                } else {
                    if (id === 3) {
                        if (this.infolist.orderType == "1") {
                            delete this.rules.approvalType;
                        }
                        this.$refs["infolist"].validate((valid) => {
                            if (valid) {
                                this.$http({
                                    url: "/market/CMKFile/CMKFileTemplateAdd",
                                    method: "post",
                                    headers: {
                                        "Content-Type": "application/json",
                                    },
                                    data: this.infolist,
                                }).then((res) => {
                                    if (res.status == 200) {
                                        this.dialogStatus = false;
                                        this.$router.go(0);
                                    }
                                });
                            } else {
                                this.$message.error("请填写必填项");
                                return false;
                            }
                        });
                    }
                }
            }
        }


    },
    //新建上传材料
    async upLoad(params) {
      let file = params.file;
      const form = new FormData();
      form.append("file", file);
      await this.$http({
        url: "/market/CMKFile/upload",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: form,
      }).then((res) => {
        if (this.infolist.mkFileShareAttachList) {
          this.infolist.mkFileShareAttachList = [];
          this.infolist.mkFileShareAttachList.push(res.data.body);
        } else {
          let mkFileShareAttachList = [];
          mkFileShareAttachList.push(res.data.body);
          this.$set(
            this.infolist,
            "mkFileShareAttachList",
            mkFileShareAttachList
          );
          this.$refs["infolist"].validateField("mkFileShareAttachList");
        }
      });
    },
    async dialogCheck() {
      this.dialogStatus = true;
      this.DisableStatusb = false;
      this.DisableStatus = false;
      this.titleName = "添加";
      // await this.$http({
      //   url: "/market/calarm/query",
      //   method: "post",
      //   headers: {
      //     "Content-Type": "application/json",
      //   },
      // }).then((res) => {
      //   this.infolist = res.data;
      //   this.treeList = res.data.sQaAlarmRuleReceiveList;
      // });
    },
    //退回
    async outClick(e) {
      e.authType = "6";
      await this.$http({
        url: "/market/CMKFile/goBack",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: e,
      }).then((res) => {
        if (res.data.result == 0) {
          this.dialogStatusss = false;
          this.dialogStatuss = false;
          this.dialogStatus = false;
          this.repltStatus = false;
          this.handleInit({ page: "1", pageSize: "10" });
        }
      });
    },
    async handleInit(data) {
      this.table_loading = true;
      await this.$http({
        url: "/market/CMKFile/CMKFileTemplateList",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: data,
      }).then(({ data: { count, data } }) => {
        this.table_loading = false;
        this.total = count;
        if (data) {
          data.map((item) => {
            const d = new Date(item.issuedTime);
            if (item.issuedTime) {
              item.issuedTime =
                d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
            }
            item.orderType = item.orderType == "0" ? "收集" : "分享";
          });
          this.table_list = data || [];
        }
      });
    },
    //回复详情
    async handReply(e) {
      this.repltStatus = true;
      let array = new FormData();
      array.append("id", e.id);
      await this.$http({
        url: "/market/CMKFile/reply",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: array,
      }).then((res) => {
        if (res.data) {
          for (let i = 0; i <= res.data.length - 1; i++) {
            res.data[i].ids = i + 1;
            if(res.data[i].subAttach === null || res.data[i].subAttach === ''){
                res.data[i].procedure = '未回复'
                res.data[i].status = '1'
            }else{
                res.data[i].procedure = '已回复'
                res.data[i].status = '0'
            }

            for (
              let y = 0;
              y <= res.data[i].mkFileShareAttachList.length - 1;
              y++
            ) {
              if (res.data[i].subAttach === null|| res.data[i].subAttch === '') {
                  res.data[i].state = '--';
              }else{
                  res.data[i].state =
                      res.data[i].mkFileShareAttachList[y].opTime +
                      res.data[i].mkFileShareAttachList[y].opName +
                      "反馈";
              }
            }
          }
        }

        this.replt_list = res.data || [];
        // if(res.data.result == 0){
        //     this.handleInit({page:'1',pageSize:'10'})
        // }
      });
    },
    //下载情况
    async handleEdit(e) {
      let array = new FormData();
      array.append("id", e.id);
      this.reditStatus = true;
      await this.$http({
        url: "/market/CMKFile/downLoadHis",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: array,
      }).then((res) => {
        if (res.data) {
          for (let i = 0; i <= res.data.length - 1; i++) {
            res.data[i].id = i + 1;
            res.data[i].opName =
              res.data[i].opTime + res.data[i].opName + "下载";
            res.data[i].download =
              res.data[i] != "" ? res.data[i].download : "--";
          }
        }

        this.download_list = res.data || [];
        // if(res.data.result == 0){
        //     this.handleInit({page:'1',pageSize:'10'})
        // }
      });
    },
    //属性选择人回显删除事件
    deletes(val, index) {

      this.infolist.receiverList.splice(index, 1);
        console.log(this.a)
    },
    //撤销时间
    async handleDelete(e) {
      let array = new FormData();
      array.append("id", e.id);
      await this.$http({
        url: "/market/CMKFile/cancel",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: array,
      }).then((res) => {
        if (res.data.result == 0) {
          this.handleInit({ page: "1", pageSize: "10" });
        }
      });
    },
    handlePreview() {},
    handleRemove() {},

    //修改
    handleDetail(e) {
      this.DisableStatusb = true;
      this.DisableStatus = true;
      this.titleName = "修改";
      this.row_id = e.id;
      let array = new FormData();
      array.append("id", e.id);
      this.$http({
        url: "/market/CMKFile/updateQuery",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: array,
      }).then((res) => {
        this.infolist = res.data.body;
        this.treeList = res.data.body.receiverList;
        window.sessionStorage.setItem('treeList',JSON.stringify(this.treeList));
        this.detail_list = res.data.body.updateList;
        this.table_loading = false;
        if (res.data.body.orderType != "0") {
          this.showStatus = true;
          delete this.rules.approvalType;
        }
      });
      //获取对应id接口
      this.dialogStatus = true;
      this.detailStatus = true;
    },
    // 搜索事件
    handleSearch(data) {
      const d = new Date(data.issuedTime);
      if (data.issuedTime) {
          const month = d.getMonth()+1<10?'0'+(d.getMonth()+1):d.getMonth()+1;
          const Date = d.getDate()<10 ?'0'+(d.getDate()+1):d.getDate()
        data.issuedTime =d.getFullYear() + "-" + month + "-" + Date;
          console.log(data.issuedTime)

      }
      if (data != "reset") {
        this.table_search = {
          ...data,
        };
        this.page = "1";
        this.handleInit({
          ...this.table_search,
          page: this.page,
          pageSize: "10",
        });
      }
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .info-line .el-form-item__content {
  display: flex !important;
}
.footer-button {
  width: 120px;
}
.detail-title {
  font-size: 20px;
  padding-bottom: 33px;
}
.onetab {
  margin-bottom: 20px;
  padding: 0 20px;
}

.titbox {
  div {
    float: right;

    i {
      font-size: 22px;
      margin-left: 20px;
      cursor: pointer;
    }
  }
}

.tabbox {
  margin-top: 15px;
}

.pageBox {
  text-align: right;
  margin-top: 10px;
}

.info-line {
  width: 100%;
  display: block;
  padding-left: 20px;

  div {
    width: 50%;
  }

  span {
    width: 100px;
    display: inline-block;
    text-align: left;

    i {
      color: red;
      display: inline-block;
      padding-right: 5px;
    }
  }

  .el-select,
  .el-input {
    width: calc(100% - 120px);
  }
}

.online {
  width: 100%;

  .el-select {
    width: calc(100% - 120px);
  }

  span {
    vertical-align: top;
  }

  .el-textarea {
    width: calc(100% - 120px);
  }

  .tree {
    width: calc(50% - 60px);
    display: inline-block;
    margin-right: 20px;
    height: 300px;
    overflow-y: scroll;

    .el-icon-error {
      float: right;
      font-size: 20px;
      margin-top: 9px;
      cursor: pointer;
    }
  }

  .treeUser {
    margin: 0;
    border: 1px solid #ddd;

    p {
      background: #f4f4f4;
      padding: 0 20px;
      margin-bottom: 5px;
    }
  }

  .treeUserb {
    width: calc(100% - 100px);
    border: 1px solid #ddd;
    background: #f4f4f4;
    border-radius: 3px;
    height: auto;
    overflow: hidden;

    p {
      display: inline-block;
      padding: 0 20px;
      margin-bottom: 5px;
    }
  }
}

.adv-type {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  // border: 1px solid #ddd;
  border-radius: 5px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  div {
    width: 33%;
    text-align: center;
    height: 80px;
    overflow: hidden;
    min-width: 100px;
    cursor: pointer;
    padding-top: 10px;
    margin: 10px 0;
  }

  div:hover {
    background: #cfe8fc;
    border-radius: 5px;
  }

  span {
    width: 100%;
    display: inline-block;
    height: 40px;

    // line-height: 40px;
    i {
      color: #0074d9;
      font-size: 36px;
    }
  }
}
</style>
