<!--
 * @Author       : yuanrunwei
 * @Date         : 2021-12-04 14:23:58
 * @LastEditors: daiqisheng
 * @LastEditTime: 2022-05-10 11:24:05
 * @FilePath     : \spfm-market-front\src\pages\main\performance\components\sheet.vue
-->
<template>
    <fullscreen :fullscreen.sync="fullscreen" class="container" style=" background-color: #ffffff">
    <div class="sheet-container">
        <div style="    margin-top: 20px; margin-left: 30px;" >
            <span style="  font-size: small;margin-right: 10px;">控制权限</span>
            <el-select v-model="state" placeholder="请选择" :disabled="this.type=='view'|| (this.type=='edit' && this.isCreater !='1') ?true:false " size="mini">
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
            </el-select>
        </div>
        <div class="flex-justify-align-end margin-bottom-20">
            <!--      <span-->
            <!--        v-if="['template'].includes(attribute)"-->
            <!--        ><span class="sheet-container-require">*</span>模板类型:</span-->
            <!--      >-->
                <div style="display: flex;
                        margin-right: 20px;
                        background: rgb(2, 135, 251);
                        padding: 2px;
                        border-radius: 4px;">
                    <el-upload
                        action
                        :http-request="request"
                        :on-change="handleChange"
                        :show-file-list="false"
                        :disabled="this.type=='view'?true:false"
                    >
                        <el-button :disabled="this.type=='view'?true:false" size="mini">选择文件</el-button>
                    </el-upload>
                    <span style="font-size: 12px;margin-right: 5px;line-height: 2">{{ fileListName }}</span>
                </div>
            <el-button
                type="danger"
                @click="handleResave"
                size="mini"
                :disabled="this.type=='view'?true:false"
            >保存</el-button
            >
<!--            :disabled="handleForbid()"-->

            <el-button  size="mini" type="danger" @click="handleDownload">导出</el-button>
            <el-button size="mini" type="primary" @click="returnList">返回</el-button>
            <el-button size="mini" type="primary" @click="handleFullscreen()">全屏显示</el-button>
            <!--      <template v-if="['edit'].includes(type)">-->

            <!--        <el-button-->
            <!--          v-if="!status || status === '2'"-->
            <!--          type="primary"-->
            <!--          @click="handleSave('2')"-->
            <!--          :disabled="handleForbid()"-->
            <!--          >暂存</el-button-->
            <!--        >-->

            <!--        <el-button-->
            <!--          v-if="addFlag === '0'"-->
            <!--          type="primary"-->
            <!--          @click="handleSave('0')"-->
            <!--          :disabled="handleForbid()"-->
            <!--          ><span>{{ id ? "提交" : "新增" }}</span-->
            <!--          ><span>{{-->
            <!--            handleForbid() ? `（请先设置权限）` : ""-->
            <!--          }}</span></el-button-->
            <!--        >-->
            <!--      </template>-->
        </div>
        <div id="luckysheet" class="sheet-container-block" ></div>
    </div>
    </fullscreen>
</template>

<script>
import luckyexcel from "luckyexcel";
import { exportExcel } from "../performance/common/export";
import simpleDialog from "../performance/components/dialog.vue";
export default {
  components: {
    simpleDialog,
  },
  props: {
      isCreater: {
          type: String,
          default: "",
      },
    type: {
      type: String,
      default: "view", // view 查看 edit 编辑
    },
    attribute: {
      type: String,
      default: "template", // template 模板 order 工单 file 文件
    },
    id: {
      default: null,
    },
    // 接收人
    receiver: {
      type: String,
      default: "",
    },
    // 模板状态按钮判断
    status: { type: String, default: "" },
      mkdirId:{
          type: String,
          default:'',
      }
  },
  data() {
    return {
        fullscreen: false,
        options: [{
            value: '1',
            label: '开启'
        },{
            value: '0',
            label: '关闭'
        }],
        state:'1',
      form: {
        charge: [
          {
            person: [],
            col_start: "",
            col_end: "",
            row_start: "",
            row_end: "",
          },
        ],
        array: [],
        type: null,
        permission_type: null,
        col_start: "",
        col_end: "",
        row_start: "",
        row_end: "",
      },
      approveForm: {
        type: "",
        comments: "",
        list: [
          {
            label: "同意",
            value: "同意",
          },
          {
            label: "不同意",
            value: "不同意",
          },
          {
            label: "其他",
            value: "3",
          },
        ],
      },
      superviserules: {
        distribute: [
          { required: true, message: "请选择派发周期", trigger: "change" },
        ],
        write: [
          { required: true, message: "请选择填报周期", trigger: "change" },
        ],
        endTime: [
          { required: true, message: "请选择截止时间", trigger: "change" },
        ],
      },
      superviseForm: {
        distribute: "", // 派单周期
        write: "", // 填写周期
        endTime: "", // 截止时间
      },
      originSuperviseForm: {},
      pickOptions: {
        disabledDate(time) {
          return time.getTime() < new Date().getTime() - 8.64e7;
        },
      },
      pickWrite: {
        disabledDate(time) {
          return time.getTime() < new Date().getTime() - 8.64e7;
        },
      },
      // 可提交标志
      addFlag: "0",
      // 督办标志
      superviseFlag: null,
      rowList: [],
      isDisable: true,
      issued_id: null,
      template_id: null,
      visible: false,
      templateType: "",
      // 督办
      supervise: false,
      manager_approve: false,
      row_list: [],
      column_list: [],
      charge_list: [],
      type_options: [
        {
          value: 1,
          label: "按行",
        },
        // {
        //     value: 2,
        //     label: "按列",
        // },
      ],
        fileListName:'未选择任何文件'
    };
  },
  methods: {
      request(){},
    handleInit() {
        console.log("-----id",this.id)

        if (this.id) {

          this.handleQuery();
      } else {
        this.handleCreate();
      }
    },
      returnList(){
          this.$emit("save");
      },
    // 填报日期
    handleWrite(value) {
      if (value) {
        let range =
          new Date().getTime() > value.getTime()
            ? new Date().getTime()
            : value.getTime();
        this.pickOptions = {
          disabledDate(time) {
            return time.getTime() < range;
          },
        };
      } else {
        this.pickOptions = {
          disabledDate(time) {
            return time.getTime() < new Date().getTime() - 864000;
          },
        };
      }
    },
    handleEnd(value) {
      if (value) {
        this.pickWrite = {
          disabledDate(time) {
            return time.getTime() > value.getTime();
          },
        };
        let write = new Date(this.superviseForm.write).getTime();
        if (this.superviseForm.write && value.getTime() < write) {
          this.superviseForm.endTime = "";
        }
      } else {
        this.pickWrite = {
          disabledDate(time) {
            return time.getTime() - 864000 < new Date().getTime();
          },
        };
      }
    },
    // // 权限选择
    // handleRadio(e){
    //     console.log(e,'e');
    // },
      handleAllow() {
          // let public_permisson = (!this.form.permission_type ||
          //     this.status === "2" ||
          //     this.status === "3") &&
          //   this.type === "edit";
          // let editable = this.row_list.includes(row) && this.column_list.includes(column);
          // // let totalBoolean = (public_permisson || editable) && this.id;
          //查看无法编辑
          return this.type=="view"?false:true;
          // let totalBoolean = public_permisson || editable;
          // return totalBoolean;
      },
    async handleQuery() {
        debugger
        const {
            data: {
                templateContent,
                templateName,
                state,
            },
        } = await this.$http({
            url: "/market/workLists/getWorkById",
            method: "post",
            headers: {
                "Content-Type": "application/json",
            },
            data: {id:this.id},
        });
console.log("&&&&&&&&&&&&&sss:",state,templateName)
        this.state=state;
      this.handleCreate({
        json: templateContent ? JSON.parse(templateContent) : {},
        name: templateName,
        type: "json",
      });
    },
    handleSupervise(data) {
      if (data === "cancel") {
        this.supervise = false;
        this.superviseForm = {
          ...this.originSuperviseForm,
        };
        return;
      }
      if (this.supervise === false) {
        this.supervise = true;
        this.originSuperviseForm = {
          ...this.superviseForm,
        };
      } else {
        let filled =
          Object.keys(this.superviseForm).length === 3 &&
          Object.values(this.superviseForm).filter((el) => el !== "").length ===
            3;
        if (filled) {
          let time = new Date().getTime();
          let endTime = new Date(this.superviseForm.endTime).getTime();
          if (time > endTime) {
            this.$message.error("截止时间不能小于当前时间");
            return;
          }
          this.superviseForm = {
            ...this.superviseForm,
            endTime: this.$formatDate(
              this.superviseForm.endTime,
              "YYYY-MM-DD HH:mm:ss"
            ), // 督办设置的截止时间
            write: this.$formatDate(this.superviseForm.write, "YYYY-MM-DD"), // 派发时间–或者叫—填报时间
          };
          this.supervise = false;
        } else {
          this.$message.error("请填写完整必要的信息");
        }
      }
    },
    async handleCreate({ file, json, type, name } = {}) {
      let that = this;
      const options = {
        container: "luckysheet",
        lang: "zh",
        showsheetbar: false,
        hook: {
          cellEditBefore: function ([
            { row_focus: row, column_focus: column },
          ]) {
            if (!that.handleAllow({ row, column })) {
              that.$message.error("查看无法编辑");
            }
          },
          // cellUpdated: function (row, column) {
          //   that.rowList.push(row);
          // },
          cellUpdateBefore: function (row, column) {
            console.log(row, column);
            if (!that.handleAllow({ row, column })) {
              return false;
            }
          },
          cellRenderAfter: function (cell, position) {
            const { r: row, c: column } = position;
            console.log();
            if (cell) {
              if (!that.handleAllow({ row, column })) {
                cell.bg = "#d5d5d5";
              } else {
                cell.bg = "#ffffff";
              }
            }
          },
          rangePasteBefore: function ([
            { row_focus: row, column_focus: column },
          ]) {
            if (!that.handleAllow({ row, column })) {
              that.$message.error("查看无法编辑");
              return false;
            }
          },
          updated: function ({ range }) {
            const middle = range.map((el) => {
              return that.paramsArr(el.row[0], el.row[1]);
            });
            let changedList = middle.join(",").split(",");
            that.rowList.push(...changedList);
          },
        },
      };
      switch (type) {
        case "file":
          if (file) {
            await new Promise((resolve) => {
              luckyexcel.transformExcelToLucky(file, (export_json) => {
                options.data = [
                  ...export_json.sheets.map((element) => ({
                    ...element,
                    zoomRatio:0.75,
                  })),
                ];
                options.title = export_json.info.name;
                resolve();
              });
            });
          }
          break;
        case "json":
          if (json) {
            options.data = [
              {
                ...json,
                zoomRatio: 0.75,
              },
            ];
            options.title = name;
          }
          break;
      }
      window.luckysheet.create(options);

      let clock = setInterval(() => {
        if (window.luckysheet) {
          window.luckysheet.refresh();
          clearInterval(clock);
        }
      }, 1000);
    },
    async handleChange(response, fileList) {
        this.fileListName = fileList.slice(-1)[0].name;
        this.handleCreate({ file: response.raw, type: "file" });
    },
    handleDownload() {
      exportExcel(
        window.luckysheet.getAllSheets(),
        window.luckysheet.getWorkbookName()
      );
    },
    async handleAddAuth({ id }) {
      // const object = {};
      const { permission_type } = this.form;
      console.log(id, permission_type);
      let reqdata = {
        templateId: id,
        type: permission_type ? 2 : 1,
      };
      if (!permission_type) {
        //  公共权限
        const { person } = this.form;

        const principalId = [];
        const principalName = [];
        const principalMent = [];
        person.forEach((el) => {
          principalMent.push(el.split(",")[0].split("-")[0]);
          principalId.push(el.split(",")[0].split("-")[1]);
          principalName.push(el.split(",")[1]);
        });
        reqdata.principalId = principalId.join(",");
        reqdata.principalName = principalName.join(",");
        reqdata.principalMent = principalMent.join(",");
      } else {
        const { charge } = this.form;
        //  特殊权限
        reqdata.specialAuth = charge.map((el) =>
          JSON.stringify({
            allowEditingColumns: `${el.col_start},${el.col_end}`,
            rowNum: `${el.row_start},${el.row_end}`,
            principalMent: el.person.split(",")[0].split("-")[0],
            principalId: el.person.split(",")[0].split("-")[1],
            principalName: el.person.split(",")[1],
          })
        );
      }
      const {
        data: { result, desc },
      } = await this.$http({
        url: this.id
          ? "/market/CMKFileTemplateAuthority/CMKFileTemplateAuthorityUpdate"
          : "/market/CMKFileTemplateAuthority/CMKFileTemplateAuthorityAdd",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: reqdata,
      });
      if (result) {
        this.$message.error(desc);
      } else {
        this.$message.success(desc);
      }
      return result;
    },
    async handleSave(type) {
      let edit_url = "";
      switch (this.attribute) {
        case "template":
          edit_url = "";
          break;
        case "order":
          edit_url = "";
          break;
        case "file":
          edit_url = "/market/CMKIssued/CMKIssuedSubmit";
          break;
      }

      const sheet_name = window.luckysheet.getSheet().name;
      const data = window.luckysheet.getSheet(sheet_name);
      const workbook_name = window.luckysheet.getWorkbookName();
      if (!this.id) {
        // 新增时添加权限
        let value = {};
        if (!this.templateType) {
          this.$message.error("请输入模板类型");
          return;
        }
        if (
          Object.values(this.superviseForm).filter((el) => el !== "").length ===
          3
        ) {
          value = {
            distributeEndTime: this.superviseForm.endTime, // 督办设置的截止时间
            distributeTime: this.superviseForm.write, // 派发时间–或者叫—填报时间
            distributeType: this.superviseForm.distribute, //派发周期类型 派发周期类型 0.月 1.季度 2.半年 3.年
            superviseFlag: 1, //督办标识 0.不是 1.是
            templateType: this.templateType, //模板类型
            templateContent: JSON.stringify(data), //文件内容
            templateName: workbook_name, //模板名称
            templateUrl: "", //文件链接
            status: type,
          };
        } else {
          value = {
            superviseFlag: 0, //督办标识 0.不是 1.是
            templateType: this.templateType, //模板类型
            templateContent: JSON.stringify(data), //文件内容
            templateName: workbook_name, //模板名称
            templateUrl: "", //文件链接
            status: type,
          };
        }
        const {
          data: { body },
        } = await this.$http({
          url: "/market/CMKFileTemplate/CMKFileTemplateAdd", // 新增
          method: "post",
          headers: {
            "Content-Type": "application/json",
          },
          data: value,
        });
        await this.handleAddAuth({ id: body });
        this.$emit("save");
      } else {
        // 职位
        let duty = JSON.parse(sessionStorage.userInfo).duty;
        if (duty === "7" && type === "0") {
          this.manager_approve = true;
        } else {
          if (type === "2") {
            // 暂存
            let value = {};
            if (!this.templateType) {
              this.$message.error("请输入模板类型");
              return;
            }
            if (
              Object.values(this.superviseForm).filter((el) => el !== "")
                .length === 3
            ) {
              value = {
                templateId: this.id,
                distributeEndTime: this.superviseForm.endTime, // 督办设置的截止时间
                distributeTime: this.superviseForm.write, // 派发时间–或者叫—填报时间
                distributeType: this.superviseForm.distribute, //派发周期类型 派发周期类型 0.月 1.季度 2.半年 3.年
                superviseFlag: 1, //督办标识 0.不是 1.是
                templateType: this.templateType, //模板类型
                templateContent: JSON.stringify(data), //文件内容
                templateName: workbook_name, //模板名称
                templateUrl: "", //文件链接
                status: type,
              };
            } else {
              value = {
                templateId: this.id,
                superviseFlag: 0, //督办标识 0.不是 1.是
                templateType: this.templateType, //模板类型
                templateContent: JSON.stringify(data), //文件内容
                templateName: workbook_name, //模板名称
                templateUrl: "", //文件链接
                status: type,
              };
            }

            await this.$http({
              url: "/market/CMKFileTemplate/UptateCMKFileTemplateById", //
              method: "post",
              headers: {
                "Content-Type": "application/json",
              },
              data: value,
            });
            this.$emit("save");
            return;
          }
          // 员工提交
          this.rowList.shift();
          let reqdata = {
            rowIndex: [...new Set(this.rowList)]
              .sort(function (a, b) {
                return a - b;
              })
              .join(","),
            rowContent: [...new Set(this.rowList)]
              .sort(function (a, b) {
                return a - b;
              })
              .map((el) => {
                return data.data[el];
              }),
          };
          await this.$http({
            url: edit_url, //提交
            method: "post",
            headers: {
              "Content-Type": "application/json",
            },
            data: {
              id: this.template_id,
              templateContent: JSON.stringify(data),
              templateName: workbook_name,
              issuedId: this.issued_id,
              rowJson: JSON.stringify(reqdata),
            },
          });
          this.$emit("save");
        }
      }
    },
    // 判断数组是否有值
    confirmArrayData(data) {
      if (data instanceof Array) {
        let flag = 0;
        if (data.length) {
          data.forEach((el) => {
            if (el instanceof Object) {
              flag = flag + 1;
            }
          });
          if (flag) {
            return true;
          } else {
            return false;
          }
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    async handleAuth() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.handleForbid()) {
            this.$message.error("请完善可编辑信息");
            return false;
          }
          if (this.id) {
            this.handleAddAuth({ id: this.id });
          }
          this.handleVisible();
        }
      });
    },
    // 通用方法用于转化全局
    paramsArr(start, end) {
      const arr = [];
      console.log(start, end);
      for (let i = Number(start); i <= Number(end); i++) {
        arr.push(i);
      }
      return arr.join(",");
    },
    filterName(id, arr) {
      return arr.filter((el) => el.secLeaderLogin === id)[0].secLeaderName;
    },
    handleCharge(type) {
      switch (type) {
        case "add":
          this.form.charge.push({
            person: "",
          });
          this.handleForbid();
          break;
        case "delete":
          this.form.charge.pop();
          this.handleForbid();
          break;
      }
    },
    handleVisible() {
      this.visible = !this.visible;
    },
    handleInput(index, name, value) {
      let reg = /^[0-9]*$/;
      if (!reg.test(value)) {
        this.form.charge[index][name] = this.form.charge[index][name].substr(
          0,
          this.form.charge[index][name].length - 1
        );
        this.$message.error("该处只能填写数字");
      }
    },
    async handleApprove(type) {
      if (type) {
        if (this.approveForm.type) {
          if (this.approveForm.type === "3" && !this.approveForm.comments) {
            this.$message.error("请输入其他审批意见");
            return;
          }
        } else {
          this.$message.error("请选择审批意见");
          return;
        }
        const sheet_name = window.luckysheet.getSheet().name;
        const data = window.luckysheet.getSheet(sheet_name);
        const workbook_name = window.luckysheet.getWorkbookName();
        // 经理提交
        this.rowList.shift();
        let reqdata = {
          rowIndex: [...new Set(this.rowList)]
            .sort(function (a, b) {
              return a - b;
            })
            .join(","),
          rowContent: [...new Set(this.rowList)]
            .sort(function (a, b) {
              return a - b;
            })
            .map((el) => {
              return data.data[el];
            }),
        };
        await this.$http({
          url: "/market/CMKIssued/CMKIssuedSubmit", // 提交
          method: "post",
          headers: {
            "Content-Type": "application/json",
          },
          data: {
            id: this.template_id,
            templateContent: JSON.stringify(data),
            templateName: workbook_name,
            issuedId: this.issued_id,
            rowJson: JSON.stringify(reqdata),
          },
        });
        let params = {
          id: this.issued_id,
          reviewOpinion:
            this.approveForm.type === "3"
              ? this.approveForm.comments
              : this.approveForm.type,
        };
        switch (type) {
          case "1":
            params = {
              ...params,
              operateName: "结束",
              status: 3,
            };
            break;
          case "4":
            params = {
              ...params,
              operateName: "转副总审批",
              reviewType: 2,
            };
            break;
          case "3":
            params = {
              ...params,
              operateName: "转总经理审批",
              reviewType: 3,
            };
            break;
        }
        await this.$http({
          url: "/market/CMKIssued/CMKIssuedCheck", // 审批
          method: "post",
          headers: {
            "Content-Type": "application/json",
          },
          data: params,
        });
        this.$message({
          type: "success",
          message: "审批成功",
        });
        this.manager_approve = false;
        this.$emit("save");
      } else {
        this.manager_approve = false;
      }
    },
    handleFullscreen() {
        this.fullscreen = !this.fullscreen

        // const element = document.body;
      // const is_fullscreen =
      //   document.fullScreen ||
      //   document.mozFullScreen ||
      //   document.webkitIsFullScreen;
      // if (!is_fullscreen) {
      //   //进入全屏,多重短路表达式
      //   (element.requestFullscreen && element.requestFullscreen()) ||
      //     (element.mozRequestFullScreen && element.mozRequestFullScreen()) ||
      //     (element.webkitRequestFullscreen &&
      //       element.webkitRequestFullscreen()) ||
      //     (element.msRequestFullscreen && element.msRequestFullscreen());
      // } else {
      //   //退出全屏,三目运算符
      //   document.exitFullscreen
      //     ? document.exitFullscreen()
      //     : document.mozCancelFullScreen
      //     ? document.mozCancelFullScreen()
      //     : document.webkitExitFullscreen
      //     ? document.webkitExitFullscreen()
      //     : "";
      // }
    },
      handleResave() {
          const sheet_name = window.luckysheet.getSheet().name;
          const data = window.luckysheet.getSheet(sheet_name);
          const workbook_name = window.luckysheet.getWorkbookName();

          let value = {
              // templateId: this.id,
              templateContent: JSON.stringify(data), //文件内容
              templateName: workbook_name, //模板名称
              templateUrl: "", //文件链接
              state: this.state,
              mkdirId: this.mkdirId
          };
          if("edit" ==this.type){
              value.id=this.id;
          }
          this.$http({
              url: "/market/workLists/saveOrUpdate",
              method: "post",
              headers: {
                  "Content-Type": "application/json",
              },
              data: value,
          }).then((res) => {
              console.log("----res",res);
              if(res.data.result==0){
                  this.$message({
                      type: "success",
                      message: "保存成功",
                  });
              }else{
                  this.$message({
                      type: "error",
                      message: res.data.body,
                  });
              }
              this.$emit("save");
          });
      },
    handleChargeList() {
      this.$http({
        url: "/market/techcentergj/queryLeaderList",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: {},
      }).then((response) => {
        // this.charge_list = response.data.map((element) => ({
        //   label: `${element.ou} ${element.secLeaderName}`,
        //   value: `${element.ou}-${element.secLeaderLogin},${element.secLeaderName}`,
        // }));
      });
    },
  },
  mounted() {
    console.log(this.attribute, "attribute");
    console.log(this.type, "type");
    this.handleInit();
    // this.handleChargeList();
  },
  destroyed() {
    window.luckysheet.destroy();
  },
};
</script>

<style lang="scss" scope>
.sheet-container {
    position: relative;
    width: 100%;
    height: 100%;
    &-block {
        overflow: hidden;
        position: absolute;
        width: 100%;
        height: 85%;
    }
  &-require {
    color: red;
  }
  .el-input {
    width: 200px;
    margin-right: 10px;
  }
}
.form {
  &-input {
    margin-top: 5px;
    .el-input {
      width: 150px;
      .el-input__inner {
        height: 30px !important;
        line-height: 30px !important;
      }
    }
  }
  &-content {
    margin: 0px 10px;
  }
  //&-select {
  //  .el-input {
  //    width: 100px;
  //    .el-input__inner {
  //      height: 30px !important;
  //      line-height: 30px !important;
  //    }
  //  }
  //}
}
</style>
