/*
 * @Overview 생산오더 별 진행 현황
 */

/*
 * @Overview 생산오더별 진행현항 vue table
 * @Parameter 없음
 * @function 데이터 입력 및 동적 렌더링
 */
const VueOperStatusCode = createApp({
  data() {
    return {
      ajaxUrl: "./sts_order.ajax.php",
      tbFilter: "",
      codeList: [],
      filterList: [],
      count:0,
      nCode: {},
      now: "",
      show:false
    };
  },
  mounted() {
    this.getMainList(
      "getStsList",
      "order_date_st",
      "order_dSDate_ed",
      "client_pop",
      "product_order_pop",
      "product_pop",
      "ITEM_NM",
      "ITEM_GRP",
      "client_pop",
      "PROC_SEQ",
      "WO_STATUS"
    );
    // this.show = false;
  },

  methods: {
    // tableBuild 되었을때 getManList
    getMainList(mode, ...test) {
      this.show = true;
      // const talert = window.setTimeout(() => {
      //   this.tbList.alert("Loading ...");
      // }, 1000);
      let arr = test;
      let data = new Object();
      for (let i = 0; i < arr.length; i++) {
        let temp = [arr[i]];
        if (document.getElementById(arr[i])?.type !== "checkbox") {
          data[temp] = document.getElementById(temp)?.value;
        } else {
          data[temp] = document.getElementById(temp)?.checked ? "Y" : "N";
        }
      }
      data.mode = mode;
      ajax_json({
        url: this.ajaxUrl,
        data: data,

        success: (data) => {
          if (data.code) {
            this.getCodeList(data.data);
          } else {
            kuls_alert(data.mesg);
          }
        },
        error: (req, status, err) => {
          kuls_alert(err.message);
        },
        complete: () => {
          // window.clearTimeout(talert);
          this.now = this.getNow();
        },
      });
      return true;
    },

    getNow(){
      const now = new Date();
      const set2spell = (num)=>{
        return num < 10 ? '0'+num : num;
      }
      return `마지막 조회시간: ${now.getFullYear()}-${set2spell(now.getMonth()+1)}-${set2spell(now.getDate())}
      ${set2spell(now.getHours())}:${set2spell(now.getMinutes())}:${set2spell(now.getSeconds())}`
    },
    parseDate(str) {
        if(str){
          const [datePart, timePart] = str.split(" ");
          const [month, day] = datePart.split(".").map(Number);
          const [hour, minute] = timePart.split(":").map(Number);

          const now = new Date();
          const year = now.getFullYear();

          return new Date(year, month - 1, day, hour, minute);
        }
    },
    //데이터 가공 함수
    getCodeList(temp) {
      // 임의의 데이터 직접 입력 [데이터 이렇게 php로 전처리...]
      let _this = this;

      let realTemp = [];
      //생산오더를 기준으로 groupBy 함수 사용
      let group = Object.values(Object.groupBy(temp, ({ WO_NO }) => WO_NO));
      //OP_CD 내부에 아래 요소들을 넣어 배열 안의 배열로 데이터를 가공
      for (let i = 0; i < group.length; i++) {
        group[i][0].OP_CD = group[i].map(function (element) {
          return {
            OP_CD: element?.OP_CD,
            ORD_QTY: element?.ORD_QTY,
            PRD_QTY: element?.PRD_QTY,
            BP_NM: element?.BP_NM,
            ST_TM: element?.ST_TM,
            ED_TM: element?.ED_TM,
            GL_TM: element?.GL_TM,
            OP_TM: element?.OP_TM,
            FACLT_NM: element?.FACLT_NM,
            EMP_NM: element?.EMP_NM,
            OP_STATUS: element?.OP_STATUS,
            isDelay: (_this.parseDate(element?.ED_TM) > _this.parseDate(element?.GL_TM)) || false
          };
        });

        realTemp.push(group[i][0]);
      }

      if (document.getElementById("PROC_SEQ").value == "DESC") {
        realTemp.sort(function (a, b) {
          return b.PROC_SEQ - a.PROC_SEQ;
        });
      } else {
        realTemp.sort(function (a, b) {
          return a.PROC_SEQ - b.PROC_SEQ;
        });
      }

      this.codeList = realTemp;
      this.count = realTemp.length;
      this.show = false;
      return this.codeList;
    },

    excelDownload(){
        // console.log(this.codeList);
        // let _this = this;
        this.show = true;
        this.getExcel('생산오더진행현황', "생산오더진행현황", this.codeList,this.codeList )
    },
    getExcel(filename, title, data,baseData) {


      if (typeof ExcelJS === "undefined") return false;
      filename = filename || "noname.xlsx";
      title = title || "제목을 입력하지 않았습니다.";
      filename = filename.replace(/[\*\?\:\\\/\[\]]/, "");

      const workBook = new ExcelJS.Workbook();
      this.getSheet(workBook, title, data,baseData);

      workBook.xlsx.writeBuffer().then((buffer) => {
        let blob = new Blob([buffer], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        let url = window.URL.createObjectURL(blob);
        let anchor = document.createElement("a");
        anchor.href = url;
        anchor.download = filename;
        anchor.click();
        window.URL.revokeObjectURL(url);
        VueOperStatusCode.show = false;
      });



      return false;
    },
    getSheet(wbook, sheetname, sheetdata,baseData) {
      const workSheet = wbook.addWorksheet(sheetname, {
        pageSetup: {
          paperSize: 9,
          fitToPage: true,
          horizontalCentered: true,
          margins: {
            left: 0.28,
            right: 0.28,
            top: 0.88,
            bottom: 0.64,
            header: 0.48,
            footer: 0.52,
          },
          orientation: "landscape",
        },
        properties: { defaultRowHeight: 18 },
      });

//<<-- 스타일 CSS 시작
      const all_border = {
        top: { style: "thin", color: { argb: "FF000000" } },
        left: { style: "thin", color: { argb: "FF000000" } },
        bottom: { style: "thin", color: { argb: "FF000000" } },
        right: { style: "thin", color: { argb: "FF000000" } },
      };
      const all_thick_border = {
        top: { style: "thick", color: { argb: "FF000000" } },
        left: { style: "thick", color: { argb: "FF000000" } },
        bottom: { style: "thick", color: { argb: "FF000000" } },
        right: { style: "thick", color: { argb: "FF000000" } },
      };
      const top_thick   = {
        top: { style: "thick", color: { argb: "FF000000" } },
        left: { style: "thick", color: { argb: "FF000000" } },
        bottom: { style: "thin", color: { argb: "FF000000" } },
        right: { style: "thick", color: { argb: "FF000000" } },
      }
      const top_thick_right   = {
        top: { style: "thick", color: { argb: "FF000000" } },
        left: { style: "thin", color: { argb: "FF000000" } },
        bottom: { style: "thin", color: { argb: "FF000000" } },
        right: { style: "thick", color: { argb: "FF000000" } },
      }
      const top_thick_left   = {
        top: { style: "thick", color: { argb: "FF000000" } },
        left: { style: "thick", color: { argb: "FF000000" } },
        bottom: { style: "thin", color: { argb: "FF000000" } },
        right: { style: "thin", color: { argb: "FF000000" } },
      }
      const left_thick  = {
        top: { style: "thin", color: { argb: "FF000000" } },
        left: { style: "thick", color: { argb: "FF000000" } },
        bottom: { style: "thin", color: { argb: "FF000000" } },
        right: { style: "thin", color: { argb: "FF000000" } },
      }
      const bottom_thick_right= {
        top: { style: "thin", color: { argb: "FF000000" } },
        left: { style: "thin", color: { argb: "FF000000" } },
        bottom: { style: "thick", color: { argb: "FF000000" } },
        right: { style: "thick", color: { argb: "FF000000" } },
      }
      const bottom_thick_left= {
        top: { style: "thin", color: { argb: "FF000000" } },
        left: { style: "thick", color: { argb: "FF000000" } },
        bottom: { style: "thick", color: { argb: "FF000000" } },
        right: { style: "thin", color: { argb: "FF000000" } },
      }
      const right_thick = {
        top: { style: "thin", color: { argb: "FF000000" } },
        left: { style: "thin", color: { argb: "FF000000" } },
        bottom: { style: "thin", color: { argb: "FF000000" } },
        right: { style: "thick", color: { argb: "FF000000" } },
      }
      const  side_thick= {
        top: { style: "thin", color: { argb: "FF000000" } },
        left: { style: "thick", color: { argb: "FF000000" } },
        bottom: { style: "thin", color: { argb: "FF000000" } },
        right: { style: "thick", color: { argb: "FF000000" } },
      }
      const  bottom_thick= {
        top: { style: "thin", color: { argb: "FF000000" } },
        left: { style: "thick", color: { argb: "FF000000" } },
        bottom: { style: "thick", color: { argb: "FF000000" } },
        right: { style: "thick", color: { argb: "FF000000" } },
      }
      const field_css = {
        top_thick_border :{
          border: top_thick,
          alignment: { vertical: "middle", horizontal: "center" },
          font: { size: 10 },
        },
        bottom_thick_border :{
          border: bottom_thick,
          alignment: { vertical: "middle", horizontal: "center" },
          font: { size: 10 },
        },
        top_right_border :{
          border: top_thick_right,
          alignment: { vertical: "middle", horizontal: "center" },
          font: { size: 10 },
        },
        top_left_border :{
          border: top_thick_left,
          alignment: { vertical: "middle", horizontal: "center" },
          font: { size: 10 },
        },
        bottom_left_border :{
          border: bottom_thick_left,
          alignment: { vertical: "middle", horizontal: "center" },
          font: { size: 10 },
        },
        bottom_right_border :{
          border: bottom_thick_right,
          alignment: { vertical: "middle", horizontal: "center" },
          font: { size: 10 },
        },
        left_border :{
          border: left_thick,
          alignment: { vertical: "middle", horizontal: "center" },
          font: { size: 10 },
        },
        right_border :{
          border: right_thick,
          alignment: { vertical: "middle", horizontal: "center" },
          font: { size: 10 },
        },
        side_border :{
          border: side_thick,
          alignment: { vertical: "middle", horizontal: "center" },
          font: { size: 10 },
        },

        yellow_left: {
          border: top_thick_left,
          font: { color: { argb: "FF9C5700" }, bold: true },
          alignment: { vertical: "middle", horizontal: "center" },
          fill: {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "FFFFEB9C" },
          },
        },
        yellow_right: {
          border: top_thick_right,
          font: { color: { argb: "FF9C5700" }, bold: true },
          alignment: { vertical: "middle", horizontal: "center" },
          fill: {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "FFFFEB9C" },
          },
        },
        green: {
          // border: all_border,
          font: { color: { argb: "FF006100" }, bold: true },
          alignment: { vertical: "middle", horizontal: "center" },
          fill: {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "FFC6EFCE" },
          },
        },
        red_left: {
          border: top_thick_left,
          font: { color: { argb: "FF9C0006" }, bold: true },
          alignment: { vertical: "middle", horizontal: "center" },
          fill: {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "ff7d7d" },
          },

        },
        red_right: {
          border: top_thick_right,
          font: { color: { argb: "FF9C0006" }, bold: true },
          alignment: { vertical: "middle", horizontal: "center" },
          fill: {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "ff7d7d" },
          },

        },
        pink_right: {
          border: right_thick,
          alignment: { vertical: "middle", horizontal: "center" },
          fill: {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "ffe0d2" },
          },
          font: { size: 10 },

        },
        blue_left: {
          border: top_thick_left,
          font: { font: { size: 11 }, color: { argb: "0E3979" }, bold: true },
          alignment: { vertical: "middle", horizontal: "center" },
          fill: {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "d2e7ff" },

          }
        },
        blue_right: {
          border: top_thick_right,
          font: { font: { size: 11 }, color: { argb: "0E3979" }, bold: true },
          alignment: { vertical: "middle", horizontal: "center" },
          fill: {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "d2e7ff" },

          }
        },
        gray_left: {
          border: top_thick_left,
          font: { font: { size: 11 }, color: { argb: "0E3979" }, bold: true },
          alignment: { vertical: "middle", horizontal: "center" },
          fill: {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "afafaf" },

          }
        },
        gray_right: {
          border: top_thick_right,
          font: { font: { size: 11 }, color: { argb: "0E3979" }, bold: true },
          alignment: { vertical: "middle", horizontal: "center" },
          fill: {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "afafaf" },

          }
        },
        title: {
          font: { size: 30, bold: true },
          alignment: { vertical: "middle", horizontal: "center" },
        },
        box: {
          border: all_border,
          alignment: { vertical: "middle", horizontal: "center" },
          font: { size: 10 },

        },
        name: {
          border: all_border,
          alignment: { vertical: "middle", horizontal: "center" },
          font: { size: 11 },

        },



      };

      //스타일 CSS 끝 ->>

      let ws_row1_1 = workSheet.getRow(1);
      ws_row1_1.height = 40;
      ws_row1_1.getCell(1).value = "생산오더";
      ws_row1_1.getCell(1).style = field_css.name;
      ws_row1_1.getCell(2).style = field_css.name;
      workSheet.mergeCells('A1:B1');

      ws_row1_1.height = 40;
      ws_row1_1.getCell(3).value = "작업순서\n작업상태";
      ws_row1_1.getCell(3).style = field_css.box;
      ws_row1_1.getCell(3).alignment = { wrapText: true };

      let tempOPArray = ['D','E','F','G','H',
        'I','J','K','L','M',
        'N','O','P','Q','R',
        'S','T','U','V','W',
        'X','Y','Z','AA','AB','AC','AD','AE']

      //header 셀 병합 반복
      for(let i = 5; i<32; i++){
        if(i%2===1){
          workSheet.mergeCells(tempOPArray[i-5]+1+':'+tempOPArray[i-4]+1);
        }

      }
      //셀 스타일 반복
      for(let i = 4; i<32; i++){
        ws_row1_1.getCell(i).style = field_css.name
      }
      for(let i = 4; i<32; i++){
        ws_row1_1.getCell(i).style = field_css.name
      }

      for(let i = 1; i<15; i++){
        ws_row1_1.getCell(i*2+3).value = '공정'+i;
      }




      baseData.forEach((data, i)=>{
        let firstRow = "";
        let secondRow = "";
        let thirdRow= "";
        let forthRow= "";
        let fifthRow= "";

        workSheet.mergeCells('A'+(i*5+3)+':'+'B'+(i*5+3));
        workSheet.mergeCells('A'+(i*5+5)+':'+'B'+(i*5+5));

        workSheet.mergeCells('C'+(i*5+2)+':'+'C'+(i*5+3));
        workSheet.mergeCells('C'+(i*5+4)+':'+'C'+(i*5+6));


        if(i === 0){
          firstRow  = workSheet.getRow(i+2);
          secondRow = workSheet.getRow(i+3);
          thirdRow  = workSheet.getRow(i+4);
          forthRow  = workSheet.getRow(i+5);
          fifthRow  = workSheet.getRow(i+6);
          for(let j=1; j<32; j++){
            firstRow.getCell(j).style = field_css.top_thick_border;
            forthRow.getCell(j).style = field_css.side_border;
            if(j%2 === 1){
              secondRow.getCell(j).style = field_css.right_border;
              thirdRow.getCell(j).style = field_css.right_border;
              forthRow.getCell(j).style  = field_css.right_border;
              fifthRow.getCell(j).style  = field_css.bottom_right_border;
            }
            if(j%2 === 0){
              secondRow.getCell(j).style = field_css.left_border;
              thirdRow.getCell(j).style = field_css.left_border;
              fifthRow.getCell(j).style  = field_css.bottom_left_border;
            }
          }
        }else{
          firstRow = workSheet.getRow(i*5+2);
          secondRow = workSheet.getRow(i*5+3);
          thirdRow = workSheet.getRow(i*5+4);
          forthRow = workSheet.getRow(i*5+5);
          fifthRow = workSheet.getRow(i*5+6);
          for(let j=1; j<32; j++){
            firstRow.getCell(j).style = field_css.top_thick_border;
            forthRow.getCell(j).style = field_css.side_border;
            if(j%2 === 1){
              secondRow.getCell(j).style = field_css.right_border;
              thirdRow.getCell(j).style = field_css.right_border;

              fifthRow.getCell(j).style  = field_css.bottom_right_border;

            }
            if(j%2 === 0){
              secondRow.getCell(j).style = field_css.left_border;
              thirdRow.getCell(j).style = field_css.left_border;

              fifthRow.getCell(j).style  = field_css.bottom_left_border;
            }
          }

        }
        const firstRowCell_1 = firstRow.getCell(1);
        const firstRowCell_2 = firstRow.getCell(2);
        const firstRowCell_3 = firstRow.getCell(3);
        const secondRowCell_1 = secondRow.getCell(1);
        const secondRowCell_2 = secondRow.getCell(2);
        const secondRowCell_3 = secondRow.getCell(3);

        const thirdRowCell_1 = secondRow.getCell(1);
        const thirdRowCell_2 = secondRow.getCell(2);
        const thirdRowCell_3 = secondRow.getCell(3);

        const forthRowCell_1 = secondRow.getCell(1);
        const forthRowCell_2 = secondRow.getCell(2);
        const forthRowCell_3 = secondRow.getCell(3);

        const fifthRowCell_1 = secondRow.getCell(1);
        const fifthRowCell_2 = secondRow.getCell(2);
        const fifthRowCell_3 = secondRow.getCell(3);

        firstRowCell_1.value = data['WO_NO'];
        firstRowCell_2.value = data['ORD_QTY'];
        firstRowCell_3.value = data['PROC_SEQ'];

        firstRowCell_1.style = field_css.name;
        firstRowCell_2.style = field_css.right_border;
        firstRowCell_1.style = field_css.top_left_border;
        firstRowCell_2.style = field_css.top_right_border;
        // firstRow.getCell(3).style = field_css.top_left_border;
        firstRowCell_3.style = field_css.top_right_border

        secondRow.getCell(1).value = data['BP_NM'];
        secondRow.getCell(1).style = field_css.left_border;
        secondRow.getCell(2).style = field_css.right_border;
        secondRow.getCell(3).style = field_css.name;

        thirdRow.getCell(1).value = data['ITEM_GRP'];
        thirdRow.getCell(1).style = field_css.left_border;

        thirdRow.getCell(2).value = data['ITEM_CD'];
        thirdRow.getCell(2).style = field_css.name;
        thirdRow.getCell(2).style = field_css.right_border;

        thirdRow.getCell(3).value = data['ORD_STATUS'];
        thirdRow.getCell(3).style = field_css.name;

        forthRow.getCell(1).value = data['ITEM_NM'];
        forthRow.getCell(1).style = field_css.left_border;
        forthRow.getCell(2).style = field_css.name;
        forthRow.getCell(2).style = field_css.right_border;
        forthRow.getCell(3).style = field_css.name;

        fifthRow.getCell(1).value = data['ORD_DT'];
        fifthRow.getCell(2).value = data['DLVY_REQ_DT'];
        fifthRow.getCell(1).style = field_css.name;
        fifthRow.getCell(1).style = field_css.left_border;
        fifthRow.getCell(2).style = field_css.right_border;
        fifthRow.getCell(3).style = field_css.bottom_right_border;
        fifthRow.getCell(1).style = field_css.bottom_left_border;
        fifthRow.getCell(2).style = field_css.bottom_right_border;
        //공정 1부터 공정 14까지 셀 병합이 필요한 부분에 대하여 mergeCell
        for(let j = 5; j<32; j++){
          if(j%2===1){
            workSheet.mergeCells(tempOPArray[j-5]+(i*5+2)+':'+tempOPArray[j-4]+(i*5+2));
            workSheet.mergeCells(tempOPArray[j-5]+(i*5+5)+':'+tempOPArray[j-4]+(i*5+5));
          }
        }

        data['OP_CD'].forEach((OPCD,i)=>{
          firstRow.getCell(i*2+4).value = OPCD['OP_CD']
          if(OPCD['OP_STATUS'] === 'F'){
            firstRow.getCell(i*2+4).style =field_css.blue_left
            firstRow.getCell(i*2+5).style =field_css.blue_right
          }
          if(OPCD['OP_STATUS'] === 'R'){
            firstRow.getCell(i*2+4).style =field_css.yellow_left
            firstRow.getCell(i*2+5).style =field_css.yellow_right
          }
          if(OPCD['OP_STATUS'] === 'S'){
            firstRow.getCell(i*2+4).style =field_css.red_left
            firstRow.getCell(i*2+5).style =field_css.red_right
          }
          if(OPCD['OP_STATUS'] === 'P'){
            firstRow.getCell(i*2+4).style =field_css.gray_left
            firstRow.getCell(i*2+5).style =field_css.gray_right
          }

          secondRow.getCell(i*2+4).value = OPCD['ORD_QTY']
          secondRow.getCell(i*2+5).value = OPCD['PRD_QTY']
          thirdRow.getCell(i*2+4).value = OPCD['ST_TM']
          thirdRow.getCell(i*2+5).value = OPCD['ED_TM']
          forthRow.getCell(i*2+4).value = OPCD['GL_TM']
          fifthRow.getCell(i*2+4).value = OPCD['FACLT_NM']
          fifthRow.getCell(i*2+5).value = OPCD['EMP_NM']
          if(this.parseDate(OPCD['ED_TM'])>this.parseDate(OPCD['GL_TM'])){
            thirdRow.getCell(i*2+5).style = field_css.pink_right
          }

        })
      })
      return workSheet;
    }
  },
}).mount("#frame_contents");
