<!--
 * @Author: zhp
 * @Date: 2023-02-14 15:02:26
 * @LastEditTime: 2023-07-21 16:35:04
 * @LastEditors: zhp
 * @Description: 
-->
<template>
  <el-drawer :title="dataForm.id ? $t('edit') : $t('add')" :visible.sync="drawer" size="50%">
    <el-form :model="dataForm" ref="dataForm" :rules="dataRule" 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-row>
        <el-form-item style="float: right;margin-right: 30px;">
          <el-button @click="handleClose()">{{ $t('cancel') }}</el-button>
          <el-button type="primary" @click="dataFormSubmit()">{{ $t('confirm') }} </el-button>
        </el-form-item>
      </el-row>
    </el-form>
    <div v-if="dataForm.id? true :false" style='margin-left: 30px;'>
      <el-button @click="getTableData()" type="primary">{{ $t('gage.tabularComputations') }}</el-button>
      <el-button @click="tabularComputationsAdd()" type="primary">{{ $t('gage.tabularComputationsAdd') }}</el-button>
      <base-table :span-method="objectSpanMethod" :table-props="tableProps" :table-data="tableData" />
      <el-table style="width: 100%" :data="getValues" :show-header="false">
        <el-table-column v-for="(item, index) in getHeaders" :key="index" :prop="item">
        </el-table-column>
      </el-table>
    </div>
    <tabularComputations-add ref="tabularComputationsAddOrUpdate" v-if="tabularComputationsAddShow"
      @refreshDataList="getTableData">
    </tabularComputations-add>
  </el-drawer>
</template>

<script>
import debounce from "lodash/debounce";
import basicAdd from "@/mixins/basic-add";
import InnerTable from "./innerTable"
import tabularComputationsAdd from "./tabularComputations-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: '速度开动率'
//   //     }
//   //   ]
//   // }
// ]
export default {
  mixins: [basicAdd],
  components: {
    tabularComputationsAdd,
  },
  data() {
    return {
      tabularComputationsAddShow:false,
      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'
      },
      drawer:false,
      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: '自校报告'
        }
      ],
      column1Arr:[],
      column1Index: 0,
      column2Arr: {},
      column2Index: 0,
      visible: false,
      data: [],
      headers: [
        {
          prop: 'meanRange',
          label: '极差均值',
        },
        {
          prop: 'meanDifference',
          label: '均值差',
        },
        {
          prop: 'upperControlLimit',
          label: '控制上限',
        },
        {
          prop: 'lowerControlLimit',
          label: '控制下限',
        },
      ],
      // 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: {
    getHeaders() {
      return this.data.reduce((pre, cur, index) => pre.concat(`value${index}`), ['title'])
    },
    getValues() {
      return this.headers.map(item => {
        return this.data.reduce((pre, cur, index) => Object.assign(pre, { ['value' + index]: cur[item.prop] }), { 'title': item.label, });
      });
    },
    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: {
    tabularComputationsAdd() {
      this.tabularComputationsAddShow = true 
      this.$nextTick(() => {
        this.$refs.tabularComputationsAddOrUpdate.init(this.dataForm.id)
      })
    },
    setrowspans() {
      // 先给所有的数据都加一个v.rowspan = 1
      this.tableData.forEach(v => {
        v.rowspan = 1;
        v.rangeAverageRowspan = 1;
      });
      // 双层循环
      for (let i = 0; i < this.tableData.length; i++) {
        // 内层循环，上面已经给所有的行都加了v.rowspan = 1
        // 这里进行判断
        // 如果当前行的id和下一行的id相等
        // 就把当前v.rowspan + 1
        // 下一行的v.rowspan - 1
        for (let j = i + 1; j < this.tableData.length; j++) {
          //此处可根据相同字段进行合并，此处是根据的id
          if (this.tableData[i].finalAverage === this.tableData[j].finalAverage) {
            this.tableData[i].rowspan++;
            this.tableData[j].rowspan--;
          }
          if (this.tableData[i].rangeAverage === this.tableData[j].rangeAverage) {
            this.tableData[i].rangeAverageRowspan++;
            this.tableData[j].rangeAverageRowspan--;
          }
        }
        // 这里跳过已经重复的数据
        i = i + this.tableData[i].rowspan - 1;
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // console.log(column)
      if (columnIndex === 0) {
        return {
          rowspan: row.rowspan,
          colspan: 1
        };
      } else if (column.label === '最终均值') {
        return {
          rowspan: row.rowspan,
          colspan: 1
        };
      }
      if (column.label === '极差均值') {
        return {
          rowspan: row.rangeAverageRowspan,
          colspan: 1
        };
      }
    },
    getTableData() {
      this.tableData = []
      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
            //   //     }
            //   //   ]
            //   // },
            // ]
            let propsData = [
              {
                prop: 'testUserName',
                label: '人员',
                align: 'center',
                subcomponent: InnerTable
              },
              {
                prop: 'orderNumber',
                label: '序号',
                align: 'center',
              },
              {
                prop: 'test',
                label: '零件',
                align: 'center',
                children: [
                  {
                    prop: 'orderAverage',
                    label: '序号均值',
                    align: 'center',
                  },
                ]
              },
              {
                prop: 'finalAverage',
                label: '最终均值',
                align: 'center'
              },
              {
                prop: 'rangeAverage',
                label: '极差均值',
                align: 'center'
              },
              {
                prop: 'partAverageMean',
                label: 'Rp零件均值极差',
                align: 'center'
              }
            ]
            Object.keys(result.data.finalPartMapList).forEach((item) => {
              propsData[2].children.push({
                label: String(item),
                prop: 'measuredData' + String(item),
                align: 'center'
              })
            })
            this.tableProps = propsData
            let orderAverageArr = []
            let rangeArr = []
            for (let i = 0; i < result.data.qmsGageGrrTesterDTOList.length; i++){
              // console.log(result.data.qmsGageGrrTesterDTOLis[i])
              Object.keys(result.data.qmsGageGrrTesterDTOList[i].orderAverage).forEach((item) => {
                orderAverageArr.push(result.data.qmsGageGrrTesterDTOList[i].orderAverage[item])
              })
              Object.keys(result.data.qmsGageGrrTesterDTOList[i].orderMapList).forEach((item) => {
                console.log(item)
               let measuredDataProp = 'measuredData' + String(item)
                arr.push({
                  testUserName: result.data.qmsGageGrrTesterDTOList[i].testUserName,
                  orderNumber: item,
                  finalAverage: '',
                  gageGrrId: result.data.qmsGageGrrTesterDTOList[i].gageGrrId,
                  partAverageMean: '',
                  [measuredDataProp]: '',
                })
              })
              Object.keys(result.data.qmsGageGrrTesterDTOList[i].range).forEach((item) => {
                rangeArr.push(result.data.qmsGageGrrTesterDTOList[i].range[item])
              })
            }
            this.tableData = arr
            // console.log(Object.keys(result.data.finalPartMapList))
            Object.keys(result.data.finalPartMapList).forEach((item) => {
              // console.log(item)
              let measuredData = 'measuredData' + String(item)
              console.log(result.data.finalPartMapList[item])
              result.data.finalPartMapList[item].forEach((ele, index) => {
                this.tableData[index][measuredData] = ele
              })
            })
            orderAverageArr.forEach((ele, index) => {
              this.tableData[index]['orderAverage'] = ele
            })
            this.tableData.forEach((ele, index) => {
              ele.partAverageMean = result.data.partAverageMean
              result.data.qmsGageGrrTesterDTOList.forEach((item, i) => {
                // console.log(item.finalAverage)
                if (this.tableData[index].testUserName === result.data.qmsGageGrrTesterDTOList[i].testUserName) {
                  ele.finalAverage = item.finalAverage
                  ele.rangeAverage = item.rangeAverage
                }
              })
            })
            // rangeArr.forEach((ele, index) => {
            //   this.data.push({
            //     range:ele
            //   })
            // })
            // console.log()
            let dataDetail = []
            dataDetail.push({
              meanRange: result.data.meanRange,
              lowerControlLimit: result.data.lowerControlLimit,
              meanDifference: result.data.meanDifference,
              upperControlLimit: result.data.upperControlLimit,
            })
            this.data = dataDetail
            console.log(this.tableProps)
            console.log(this.tableData)
            this.setrowspans()
            // 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.drawer = 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(() => { })
    },
    handleClose() {
      this.drawer = false
      this.$refs.dataForm.resetFields()
    },
    dataFormSubmit() {
      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: () => {
                this.drawer = false
                this.$refs.dataForm.resetFields()
                this.$emit("refreshDataList")
              },
            });
          })
          .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>
