<!--
 * @Author       : yuanrunwei
 * @Date         : 2021-12-04 14:23:58
 * @LastEditors: daiqisheng
 * @LastEditTime: 2022-04-25 19:11:41
 * @FilePath     : \spfm-market-front\src\pages\main\performance\components\sheet.vue
-->
<template>
  <div class="sheet-container">
    <div>
      <el-button type="primary" v-if="saveStatus" @click="handleResave">保存</el-button>
        <!-- <el-button type="primary" @click="handleResave">保存</el-button> -->
      <!-- <el-button> <input style="font-size:16px;" type="file" @change="handdaoru(e)" /></el-button> -->
      <el-button type="primary" @click="handleDownload">导出</el-button>
      <el-button type="primary" @click="handleFullscreen()">全屏显示</el-button>
    </div>
    <div id="luckysheet" style="width: 100%; height: 100%"></div>
  </div>
</template>

<script>
import luckyexcel from "luckyexcel";
import { exportExcel } from "./export.js";
// import simpleDialog from "./dialog.vue";z
export default {
  components: {
    // simpleDialog,
  },
  props: {
    excel:{
     type:Array
    },
    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: "" },
  },
  data() {
    return {
      saveStatus: false,
      celldata: [
        { r: 0, c: 0, v: { v: "运营商", bl: 1, ht: 0, vt: 0 } },
        {
          r: 0,
          c: 1,
          tb: 2,
          v: {
            tb: 2,
            fs: 11,
            ht: 0,
            vt: 0,
            v: "套餐档位（从低到高进行填写）低档：58元以下套餐中档：58元（含）-128元套餐（不含）高档：128元及以上套餐",
            ct: { fa: "General", t: "n" },
            m: "2",
          },
        },
        {
          r: 0,
          c: 2,
          v: {
            fc: "rgb(51, 51, 51)",
            ht: 0,
            vt: 0,
            v: "套餐名称",
            ct: { fa: "General", t: "n" },
            m: "3",
          },
        },
        {
          r: 0,
          c: 3,
          v: {
            bl: 0,
            it: 0,
            ff: 0,
            fs: 11,
            fc: "rgb(51, 51, 51)",
            ht: 0,
            vt: 0,
            v: "是否为主推套餐",
            ct: { fa: "General", t: "n" },
            m: "0",
          },
        },
        {
          r: 0,
          c: 4,
          v: {
            v: "月费(元)",
            bl: 0,
            it: 0,
            ff: 0,
            fs: 11,
            fc: "rgb(51, 51, 51)",
            ht: 0,
            vt: 0,
          },
        },
        {
          r: 0,
          c: 5,
          v: {
            v: "优惠价",
            bl: 0,
            it: 0,
            ff: 0,
            fs: 11,
            fc: "rgb(51, 51, 51)",
            ht: 0,
            vt: 0,
          },
        },
        {
          r: 0,
          c: 6,
          v: {
            v: "预存款(元)",
            bl: 0,
            it: 0,
            ff: 0,
            fs: 11,
            fc: "rgb(51, 51, 51)",
            ht: 0,
            vt: 0,
          },
        },
        {
          r: 0,
          c: 7,
          v: {
            v: "套餐内容",
            bl: 0,
            it: 0,
            ff: 0,
            fs: 11,
            fc: "rgb(51, 51, 51)",
            ht: 0,
            vt: 0,
          },
        },
        {
          r: 0,
          c: 8,
          v: {
            v: "酬金",
            bl: 0,
            it: 0,
            ff: 0,
            fs: 11,
            fc: "rgb(51, 51, 51)",
            ht: 0,
            vt: 0,
          },
        },
        {
          r: 0,
          c: 9,
          v: {
            v: "在售区域",
            bl: 0,
            it: 0,
            ff: 0,
            fs: 11,
            fc: "rgb(51, 51, 51)",
            ht: 0,
            vt: 0,
          },
        },
        {
          r: 0,
          c: 10,
          v: {
            v: "在售渠道",
            bl: 0,
            it: 0,
            ff: 0,
            fs: 11,
            fc: "rgb(51, 51, 51)",
            ht: 0,
            vt: 0,
          },
        },
        {
          r: 0,
          c: 11,
          v: {
            v: "月销量",
            bl: 0,
            it: 0,
            ff: 0,
            fs: 11,
            fc: "rgb(51, 51, 51)",
            ht: 0,
            vt: 0,
          },
        },
        {
          r: 0,
          c: 12,
          v: {
            v: "是否包含宽带",
            bl: 0,
            it: 0,
            ff: 0,
            fs: 11,
            fc: "rgb(51, 51, 51)",
            ht: 0,
            vt: 0,
          },
        },
        {
          r: 0,
          c: 13,
          v: {
            v: "宽带具体内容",
            bl: 0,
            it: 0,
            ff: 0,
            fs: 11,
            fc: "rgb(51, 51, 51)",
            ht: 0,
            vt: 0,
          },
        },
        {
          r: 0,
          c: 14,
          v: {
            v: "是否包括电视",
            bl: 0,
            it: 0,
            ff: 0,
            fs: 11,
            fc: "rgb(51, 51, 51)",
            ht: 0,
            vt: 0,
          },
        },
        {
          r: 0,
          c: 15,
          v: {
            v: "是否包括副卡",
            bl: 0,
            it: 0,
            ff: 0,
            fs: 11,
            fc: "rgb(51, 51, 51)",
            ht: 0,
            vt: 0,
          },
        },
        {
          r: 0,
          c: 16,
          v: {
            v: "是否包括亲情网",
            bl: 0,
            it: 0,
            ff: 0,
            fs: 11,
            fc: "rgb(51, 51, 51)",
            ht: 0,
            vt: 0,
          },
        },
        {
          r: 0,
          c: 17,
          v: {
            v: "是否包括v网产品",
            bl: 0,
            it: 0,
            ff: 0,
            fs: 11,
            fc: "rgb(51, 51, 51)",
            ht: 0,
            vt: 0,
          },
        },
        {
          r: 0,
          c: 18,
          v: {
            v: "其他补充信息",
            bl: 0,
            it: 0,
            ff: 0,
            fs: 11,
            fc: "rgb(51, 51, 51)",
            ht: 0,
            vt: 0,
          },
        },
        {
          r: 0,
          c: 19,
          v: {
            v: "上报人",
            bl: 0,
            it: 0,
            ff: 0,
            fs: 11,
            fc: "rgb(51, 51, 51)",
            ht: 0,
            vt: 0,
          },
        },
        {
          r: 0,
          c: 20,
          v: {
            v: "联系电话",
            bl: 0,
            it: 0,
            ff: 0,
            fs: 11,
            fc: "rgb(51, 51, 51)",
            ht: 0,
            vt: 0,
          },
        },
      ],
      excelList:'',
      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: "按列",
        // },
      ],
    };
  },
  methods: {
    handdaoru(event) {
      alert(event);
      //  luckyexcel.transformExcelToLuckyByUrl(
      //   url,
      //   function (exportJson, luckysheetfile) {
      //     if (exportJson.sheets == null || exportJson.sheets.length == 0) {
      //       alert(
      //         "Failed to read the content of the excel file, currently does not support xls files!"
      //       );
      //       return;
      //     }
      //     window.luckysheet.destroy();
      //     window.luckysheet.create({
      //       container: "luckysheet",
      //       data: exportJson.sheets,
      //       title: exportJson.info.name,
      //       userInfo: exportJson.info.name.creator,
      //       lang: "zh",
      //       showinfobar: false,
      //       showtoolbar: false,
      //       allowEdit: false,
      //       allowCopy: false,
      //       editMode: true,
      //     });
      //   }
      // );
    },
    handleInit() {
      if (this.id) {
        this.handleQuery();
      } else {
        // this.handleCreate();
      }
    },
    async handleCreate(data, file) {
      console.log(data);
      let that = this;
      const options = {
        container: "luckysheet",
        lang: "zh",
        column: 10,
        row: 10,
        showsheetbar: true,
        title: "上报",
        hook: {
          cellEditBefore: function () {
            let time = new Date();
            let hover = time.getHours();
            let day = time.getDay();
            if (day === 4 || day === 5) {
              if ((day === 4 && hover < 15) || (day === 5 && hover > 15)) {
                that.$message.error("不在可编辑时间");
              }
            } else {
              that.$message.error("不在可编辑日期");
            }
          },
        },
        data: data,
        // 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);
        //   },
        // },
      };
      // let type = null;
      // 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":
      //     console.log(123);
      //     // if (json) {
      //     //   options.data = [];
      //     //   options.title = name;
      //     // }
      //     break;
      // }
      window.luckysheet.create(options);

      // let clock = setInterval(() => {
      //   if (window.luckysheet) {
      //     window.luckysheet.refresh();
      //     clearInterval(clock);
      //   }
      // }, 1000);
    },
    // async handleChange(response) {
    //   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");
        }
      }
    },
    // 获取excel数据

    handleFullscreen() {
      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 datas = window.luckysheet.getSheet(sheet_name);
      const workbook_name = window.luckysheet.getWorkbookName();
      let value = {};
      let data = datas;
      let name = JSON.parse(window.sessionStorage.getItem("userInfo")).cityName;
      if (!name) {
        data.name = "十三地市汇总";
      }
      // if (name.length === 4) {
      //   data.name = name.substring(0, 1);
      // } else if (name.length === 5) {
      //   data.name = name.substring(0, 2);
      // } else {
      //   data.name = name.substring(0, 3);
      // }

      // switch (data.name) {
      //   case null:
      //     data.index = 0;
      //     break;
      //   case "哈尔滨":
      //     data.index = 4;
      //     break;
      //   case "七台河":
      //     data.index = 13;
      //     break;
      //   case "伊春":
      //     data.index = 1;
      //     break;
      //   case "佳木斯":
      //     data.index = 2;
      //     break;
      //   case "双鸭山":
      //     data.index = 3;
      //     break;
      //   case "大兴安岭":
      //     data.index = 5;
      //     break;
      //   case "大庆":
      //     data.index = 6;
      //     break;
      //   case "牡丹江":
      //     data.index = 7;
      //     break;
      //   case "绥化":
      //     data.index = 8;
      //     break;
      //   case "鸡西":
      //     data.index = 9;
      //     break;
      //   case "鹤岗":
      //     data.index = 10;
      //     break;
      //   case "黑河":
      //     data.index = 11;
      //     break;
      //   case "齐齐哈尔":
      //     data.index = 12;
      //     break;
      // }

      value = {
        data: data, //文件内容
      };
      // }
        let time = new Date()
        let hover = time.getHours()
        console.log(hover);
        let day = time.getDay()
        if(day === 4 || day === 5){
            if((day === 4 && hover <15) || (day === 5 &&hover>15)){
                this.$message.error('不在可编辑时间');
            }else{
                this.$http({
                    url: "/market/mkCompetitor/save",
                    method: "post",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    data: value,
                }).then(() => {
                    this.$message({
                        type: "success",
                        message: "保存成功",
                    });
                    this.$emit("save",true);
                });
            }
        }else{
            this.$message.error("不在可编辑日期");
        }
      // this.$http({
      //   url: "/market/mkCompetitor/save",
      //   method: "post",
      //   headers: {
      //     "Content-Type": "application/json",
      //   },
      //   data: value,
      // }).then(() => {
      //   this.$message({
      //     type: "success",
      //     message: "保存成功",
      //   });
      //   this.getExcelList();
      //   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() {
    this.handleInit();
    this.handleChargeList();
    if (JSON.parse(window.sessionStorage.getItem("userInfo")).cityName) {
      this.saveStatus = true;
      
    }
  },
  watch:{
   excel:{
    //  immediate:true,
     handler(val){
      this.excelList = val
        
     }
   },
   excelList:{
     handler(newVal,oldVal){
       if(oldVal == ''){
        this.handleCreate(newVal)
       }
     
     }
   }
  },
  destroyed() {
    window.luckysheet.destroy();
  },
};
</script>

<style lang="scss" scope>
.el-dialog {
  width: 100%;
  height: 100%;
  margin-top: 0 !important;
}
.sheet-container {
  position: fixed;
  width: 96%;
  height: 80%;
  &-block {
    overflow: hidden;
    position: absolute;
    width: 100%;
    height: 75%;
  }
  &-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>
