<!--
 * @Author: zhp
 * @Date: 2023-02-14 15:02:26
 * @LastEditTime: 2023-07-13 09:42:39
 * @LastEditors: zhp
 * @Description: 
-->
<template>
  <el-form :model="dataForm" ref="dataForm"  :rules="dataRule" @keyup.enter.native="dataFormSubmitHandle()"
    label-width="150px">
    <el-row>
      <el-col :span="8">
        <el-form-item prop="partName" :label="$t('gage.partName')">
          <el-input v-model="dataForm.partName" :placeholder="$t('gage.partName')">
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="gageId" :label="$t('gage.gageName')">
          <el-select v-model="dataForm.gageId" :placeholder="$t('gage.gageName')" @change="getGageType">
            <el-option v-for="item in gageList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="corporation" :label="$t('gage.corporation')">
          <el-input v-model="dataForm.corporation" :placeholder="$t('gage.corporation')">
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="8">
        <el-form-item prop="itemNo" :label="$t('gage.itemNo')">
          <el-input v-model="dataForm.itemNo" :placeholder="$t('gage.itemNo')">
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="gageTypeName" :label="$t('gage.gageTypeName')">
          <el-input v-model="dataForm.gageTypeName" :placeholder="$t('gage.gageTypeName')" disabled>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="partNumber" :label="$t('gage.partNumber')">
          <el-input v-model="dataForm.partNumber" :placeholder="$t('gage.partNumber')">
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="8">
        <el-form-item prop="specification" :label="$t('gage.specification')">
          <el-input v-model="dataForm.specification" :placeholder="$t('gage.specification')">
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="measuringToolSpecification" :label="$t('gage.measuringToolSpecification')">
          <el-input v-model="dataForm.measuringToolSpecification" :placeholder="$t('gage.measuringToolSpecification')"
            disabled>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="process" :label="$t('gage.process')">
          <el-input v-model="dataForm.process" :placeholder="$t('gage.process')">
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="8">
        <el-form-item prop="measurementNumber" :label="$t('gage.measurementNumber')">
          <el-input v-model="dataForm.measurementNumber" :placeholder="$t('gage.measurementNumber')">
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="measuringToolAccuracy" :label="$t('gage.measuringToolAccuracy')">
          <el-input v-model="dataForm.measuringToolAccuracy" :placeholder="$t('gage.measuringToolAccuracy')">
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="fabrication" :label="$t('gage.fabrication')">
          <el-input v-model="dataForm.fabrication" :placeholder="$t('gage.fabrication')">
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="8">
        <el-form-item prop="publicErrand" :label="$t('gage.publicErrand')">
          <el-input v-model="dataForm.publicErrand" :placeholder="$t('gage.publicErrand')">
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="precisionDecimalPlace" :label="$t('gage.precisionDecimalPlace')">
          <el-input v-model="dataForm.precisionDecimalPlace" :placeholder="$t('gage.precisionDecimalPlace')">
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="tester" :label="$t('gage.tester')">
          <el-input v-model="dataForm.tester" :placeholder="$t('gage.tester')">
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="8">
        <el-form-item prop="precisionDecimalPlace" :label="$t('gage.precisionDecimalPlace')">
          <el-input v-model="dataForm.precisionDecimalPlace" :placeholder="$t('gage.precisionDecimalPlace')">
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="measurementTime" :label="$t('gage.measurementTime')">
          <el-date-picker v-model="dataForm.measurementTime" type="datetime" :placeholder="$t('gage.measurementTime')"
            format='yyyy-MM-dd HH:mm:ss' valueFormat='yyyy-MM-ddTHH:mm:ss'>
          </el-date-picker>
        </el-form-item>
      </el-col>
    </el-row>
    <el-button @click="getTableData()" type="primary">{{ $t('gage.tabularComputations') }}</el-button>
    <base-table :table-props="tableProps" :table-data="tableData" />
  </el-form>
</template>

<script>
import debounce from "lodash/debounce";
import basicAdd from "@/mixins/basic-add";
import available from "./available";
// const tableProps = [
//   {
//     prop: 'equipmentName',
//     label: '设备名称'
//   },
//   // {
//   //   prop: 'lineA',
//   //   label: '有效时间(h)',
//   //   children: [
//   //     {
//   //       prop: 'workTime',
//   //       label: '工作时长'
//   //     },
//   //     {
//   //       prop: 'workTimeRate',
//   //       label: '工作时长比率'
//   //     }
//   //   ]
//   // },
//   // {
//   //   prop: 'lineB',
//   //   label: '关机时间(h)',
//   //   children: [
//   //     {
//   //       prop: 'downTime',
//   //       label: '停机时长'
//   //     },
//   //     {
//   //       prop: 'downTimeRate',
//   //       label: '停机时长比率'
//   //     }
//   //   ]
//   // },
//   // {
//   //   prop: 'lineC',
//   //   label: '中断损失',
//   //   children: [
//   //     {
//   //       prop: 'faultTime',
//   //       label: '故障时长'
//   //     },
//   //     {
//   //       prop: 'faultTimeRate',
//   //       label: '故障时长比率'
//   //     }
//   //   ]
//   // },
//   // {
//   //   prop: 'lineD',
//   //   label: '速度损失',
//   //   children: [
//   //     {
//   //       prop: 'actualProcessingSpeed',
//   //       label: '实际加工速度'
//   //     },
//   //     {
//   //       prop: 'theoreticalProcessingSpeed',
//   //       label: '理论加工速度'
//   //     },
//   //     {
//   //       prop: 'speedActuationRate',
//   //       label: '速度开动率'
//   //     }
//   //   ]
//   // }
// ]
const tableProps = [
  {
    prop: 'testUserName',
    label: '人员',
    align: 'center'
  },
  {
    prop: 'orderNumber',
    label: '序号',
    align:'center'
  },
  {
    prop: 'test',
    label: '零件',
    align: 'center',
    children: [
    ]
  }
]
export default {
  mixins: [basicAdd],
  data() {
    return {
      urlOptions: {
        submitURL: "/gage/qmsGageGrr",
        infoURL: "/gage/qmsGageGrr/{ id }",
        dictionaryDetailList: '/mutual/qmsDataDictionaryDetail/page',
        getUserList: '/sys/user/page',
        getGageTypeList: '/gage/qmsGageType/page',
        getGageList: '/gage/qmsGage/page',
        getCustomerListURL: '/basic/qmsCustomer/page',
        getTabularComputationsURL: '/gage/qmsGageGrrTester/table'
      },
      trueTableProps: [],
      gageList: [],
      userList: [],
      tableProps,
      customerList: [],
      tableData:[],
      gageTypeList:[],
      departmentList: [],
      processList: [
        {
          id: 0,
          name: '未审核'
        },
        {
          id: 1,
          name: '不同意'
        },
        {
          id: 2,
          name: '同意'
        }
      ],
      listQuery: {
        limit: 999,
        page: 1
      },
      gageStatusList: [
        {
          id: 0,
          name:'在用'
        },
        {
          id: 1,
          name: '备用'
        },
        {
          id: 2,
          name: '停用'
        },
        {
          id: 3,
          name: '封存'
        },
        {
          id: 4,
          name: '报废'
        },
        {
          id: 5,
          name: '降级使用'
        }
      ],
      certificateTypeList: [
        {
          id: 0,
          name: '检定证书'
        },
        {
          id: 1,
          name: '校准证书'
        },
        {
          id: 2,
          name: '检测报告'
        },
        {
          id: 3,
          name: '自校报告'
        }
      ],
      visible: false,
      // tableProp2,
      chartDataArr: [],
      dataForm: {
        connection:null,
        corporation: null,	
        fabrication: null,	
        gageId: null,
        gageName: null,
        gageTypeName: null,
        id: null,
        itemNo: null,
        measurementNumber: null,
        measurementTime: null,
        measuringToolAccuracy: null,
        measuringToolSpecification: null,
        partName: null,
        partNumber: null,
        precisionDecimalPlace: null,
        process: null,
        publicErrand: null,
        remark: null,
        specification: null,
        tester: null,
      },
    };
  },
  computed: {
    dataRule() {
      return {
        publicErrand: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        gageId: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        measurementNumber: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        partNumber: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ]
      };
    },
  },
  mounted () {
    this.getData();
  },
  destroyed () {
    this.tableData = []
    this.tableProps = []
  },
  methods: {
    getTableData() {
      this.$http.get(this.urlOptions.getTabularComputationsURL, {
        params: {
          gageGrrId:this.dataForm.id
        },
      })
        .then(({ data: result }) => {
          if (result.code === 0) {
            console.log(result)
            let arr = []
            // let aa = []
            // let moreData = [
            //   // {
            //   //   testUserName: null,
            //   //   data: [
            //   //     {
            //   //       orderNumber: result.data.qmsGageGrrTesterDTOList[i].list[j].orderNumber,
            //   //       data: aa
            //   //     },
            //   //     {
            //   //       equipmentName: '机器人投入数',
            //   //       data: aa
            //   //     },
            //   //     {
            //   //       equipmentName: '良品总投入数',
            //   //       data: aa
            //   //     },
            //   //     {
            //   //       equipmentName: '工序损耗',
            //   //       data: aa
            //   //     }
            //   //   ]
            //   // },
            // ]
            for (let i = 0; i < result.data.qmsGageGrrTesterDTOList.length; i++){
              // console.log(result.data.qmsGageGrrTesterDTOList[i].orderMapList)
              Object.keys(result.data.qmsGageGrrTesterDTOList[i].partMapList).forEach((item) => {
                this.tableProps[2].children.push({
                  label: String(item),
                  prop: 'measuredData' + String(item),
                  align: 'center'
                })
              })
              Object.keys(result.data.qmsGageGrrTesterDTOList[i].orderMapList).forEach((item) => {
               let measuredDataProp = 'measuredData' + String(item)
                this.tableData.push({
                  testUserName: result.data.qmsGageGrrTesterDTOList[i].testUserName,
                  orderNumber: item,
                  [measuredDataProp]: '',
                })
                })
                Object.keys(result.data.qmsGageGrrTesterDTOList[i].orderMapList).forEach((item) => {
                  result.data.qmsGageGrrTesterDTOList[i].orderMapList[item].forEach((ele, index, arr) => {
                    let measuredData = 'measuredData' + String(index + 1)
                    console.log(item)
                    // console.log(arr)
                    // console.log(ele)
                    // console.log(this.tableProps[2].children.prop);
                    // console.log(this.tableProps[2].children[item - 1].prop)
                    console.log(index)
                    console.log(measuredData)
                    console.log(ele)
                    // console.log(this.tableData[index + 1])
                    this.tableData[item-1][measuredData] = ele
                    // console.log(this.tableData[item - 1])       
                  })
              })
            }
            console.log(this.tableProps)
            console.log(this.tableData)
            // console.log(this.table)
            // console.log(moreData,'1111')
            // for (let i = 0; i < 30; i++) {
            //   let a = {
            //     time: '2022-11-' + i,
            //     eqCT: 0.01,
            //     eqTT: 0.62,
            //     lineCT: 0.73,
            //     lineTT: 0.45
            //   }
            //   aa.push(a)
            // }
            // this.numArr = []
            // let num = 0
            // const tableConfig = []
            // this.chartDataArr = []
            // const dataArr = moreData.map((item, index) => {
            //   let dataArr = []
            //   if (item.data) {
            //     this.chartDataArr = this.chartDataArr.concat(item.data)
            //     num += item.data.length
            //     this.numArr.push(num)
            //     dataArr = item.data.map((z, idx) => {
            //       const dataArr = {}
            //       z.data.forEach((i) => {
            //         // 动态生成tableConfig
            //         if (index === 0 && idx === 0) {
            //           tableConfig.push({
            //             label: i.time,
            //             prop: i.time,
            //             children: [
            //               { prop: i.time + 'eqCT', label: '设备CT', subcomponent: available },
            //               { prop: i.time + 'eqTT', label: '设备TT' },
            //               { prop: i.time + 'lineCT', label: '产线CT' },
            //               {
            //                 prop: i.time + 'lineTT',
            //                 label: '产线TT',
            //                 // subcomponent: demo3Sub
            //               }
            //             ]
            //           })
            //         }
            //         // 合并数据集
            //         dataArr[i.time + 'eqCT'] = i.eqCT
            //         dataArr[i.time + 'eqTT'] = i.eqTT
            //         dataArr[i.time + 'lineCT'] = i.lineCT
            //         dataArr[i.time + 'lineTT'] = i.lineTT
            //         dataArr.testUserName = item.testUserName
            //         dataArr.orderNumber = z.orderNumber
            //       })
            //       console.log(dataArr)
            //       return dataArr
            //     })
            //   }
            //   return dataArr
            // })
            // console.log(tableConfig)
            // this.trueTableProps = this.tableProp2.concat(tableConfig)
            // console.log(this.trueTableProps,'22112112')
            // this.tableData = this.flatten(dataArr)
            // console.log(this.tableData)
          }
        })
        .catch(() => {
        })

    },
    // tree->[]
    flatten(arr) {
      var res = []
      for (var i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i])) {
          res = res.concat(this.flatten(arr[i]))
        } else {  
          res.push(arr[i])
        }
      }
      return res
    },
    spanMethod({ rowIndex, columnIndex }) {
      if (columnIndex === 1) {
        if (rowIndex === 0) {
          return [this.numArr[0], 1]
        } else if (this.numArr.indexOf(rowIndex) >= 0) {
          const rowNum =
            this.numArr[this.numArr.indexOf(rowIndex) + 1] -
            this.numArr[this.numArr.indexOf(rowIndex)]
          return [rowNum, 1]
        } else {
          return [0, 0]
        }
      }
    },
    init(id, ) {
      this.dataForm.id = id || ""
      // console.log(11111)
      // this.dataForm.dictTypeId = dictTypeId || "";
      this.visible = true
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.getInfo()
        } else {
          // this.getCode()
        }
      });
    },
    getGageType() {
      this.gageList.forEach(ele => {
        if (val === ele.id) {
          this.dataForm.gageTypeName = ele.gageTypeName
          this.dataForm.measuringToolSpecification = ele.measuringToolSpecification
          this.dataForm.measuringToolAccuracy = ele.measuringToolAccuracy
        }
      });
    },
    getData() {
      this.$http.get(this.urlOptions.getGageList, {
          params: this.listQuery,
        })
        .then(({ data: res }) => {
          if (res.code === 0) {
            console.log(res.data)
            this.gageList = res.data.list
          }
        })
        .catch(() => {
        })
      this.$http
        .get(this.urlOptions.getUserList, this.listQuery)
        .then(({ data: res }) => {
          if (res.code === 0) {
            console.log(res.data);
            this.userList = res.data.list
          }
        })
        .catch(() => {
        })
    },
    // getCode() {
    //   this.$http.post(this.urlOptions.getCodeURL)
    //     .then(({ data: res }) => {
    //       if (res.code === 0) {
    //         console.log(res);
    //         this.dataForm.customSamplingCode = res.data
    //       }
    //     })
    //     .catch(() => {
    //     });
    // },
    // 获取信息
    getInfo() {
      this.$http
        .get(`/gage/qmsGageGrr/${this.dataForm.id}`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data,
          };
        })
        .catch(() => { })
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }
          this.$http[!this.dataForm.id ? "post" : "put"](this.urlOptions.submitURL, this.dataForm)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  console.log(1111);
                  this.visible = false;
                  this.$emit("successSubmit");
                },
              });
            })
            .catch(() => {});
        });
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
};
</script>
