<template>
  <div>
    <el-card>
      <div class="search-container">
        <span class="show-text">生产订单:</span>
        <el-input v-model="orderNo" placeholder="请输入生产订单" clearable style="width: 150px;margin-right: 10px" />
        <span class="show-text">销售订单:</span>
        <el-input v-model="contractNo" placeholder="请输入销售订单" clearable style="width: 150px;margin-right: 10px" />
        <span class="show-text">产品编码:</span>
        <el-input v-model="productCode" placeholder="请输入产品编码" clearable style="width: 150px;margin-right: 10px" />
        <span class="show-text">产品名称:</span>
        <el-input v-model="productName" placeholder="请输入产品名称" clearable style="width: 150px;margin-right: 10px" />
        <span class="show-text">工序名称:</span>
        <el-input v-model="processName" placeholder="请输入工序名称" clearable style="width: 150px;margin-right: 10px" />
        <br>
        <br>
        <span class="show-text">性质:</span>
        <el-input v-model="nature" placeholder="请输入性质" clearable style="width: 150px;margin-right: 10px" />
        <span class="show-text">排产状态:</span>
        <el-select v-model="productionStatus" clearable placeholder="请选择状态" style="width: 150px;margin-right: 10px">
          <el-option label="全部" value="全部" />
          <el-option label="已完成" value="已完成" />
          <el-option label="未完成" value="未完成" />
        </el-select>
        <span class="show-text">计划开始:</span>
        <el-date-picker
          v-model="planStartTime"
          :clearable="false"
          end-placeholder="结束时间"
          format="yyyy-MM-dd"
          popper-class="virtual-cell-time-picker"
          range-separator="-"
          start-placeholder="开始时间"
          style="width: 280px;vertical-align: top"
          type="datetimerange"
          value-format="yyyy-MM-dd" />
          <span class="show-text">计划完成:</span>
        <el-date-picker
          v-model="planendTime"
          :clearable="false"
          end-placeholder="结束时间"
          format="yyyy-MM-dd"
          popper-class="virtual-cell-time-picker"
          range-separator="-"
          start-placeholder="开始时间"
          style="width: 280px;vertical-align: top"
          type="datetimerange"
          value-format="yyyy-MM-dd" />
        <span class="show-text">要求完工日期:</span>
        <el-date-picker v-model="completionTime" :clearable="false" end-placeholder="结束时间" format="yyyy-MM-dd"
          range-separator="-" start-placeholder="开始时间" style="width: 280px;vertical-align: top" type="datetimerange"
          value-format="yyyy-MM-dd" />
        <el-button :disabled="loading" icon="el-icon-search" plain type="primary" @click="searchTable()">查询</el-button>
        
      </div>

      <el-table v-loading="loading" :data="tableData" :height="'67vh'" border
        element-loading-background="rgba(0, 0, 0, 0.2)" element-loading-spinner="el-icon-loading" highlight-current-row
        size="mini" style="width: 100%;margin-top: 20px;" tooltip-effect="dark" @row-click="handleRowClick">
        
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-form label-position="left" class="demo-table-expand">
              <el-table :data="scope.row.子数据" :row-class-name="getHeaderClass" border >
                <el-table-column  align="center" label="序号" type="index" width="50"  />
                <el-table-column align="center" label="工序名称" prop="工序名称" width="100" />
                <el-table-column align="center" label="计划数量" prop="计划数量" width="100" />
                <el-table-column align="center" label="指派对象" prop="指派对象" width="100" />
                <el-table-column align="center" label="开始时间" prop="计划开始时间" width="100">
                  <template slot-scope="scope">{{ formatDate(scope.row.计划开始时间) }}</template>
                </el-table-column>
                <el-table-column align="center" label="结束时间" prop="计划完成时间" width="100">
                  <template slot-scope="scope">{{ formatDate(scope.row.计划完成时间) }}</template>
                </el-table-column>
                <el-table-column align="center" label="完成进度" prop="进度" width="100" />
                <!-- <el-table-column align="center" label="拆分内码" prop="拆分内码" width="100" /> -->
                
              </el-table>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column align="center" label="序号" type="index" width="50"  />
        <el-table-column align="center" prop="合同号" label="销售订单" width="120"  />
        <el-table-column align="center" prop="订单号" label="生产订单" width="100"  />
        <el-table-column align="center" prop="产品编码" label="产品编码" width="220" />
        <el-table-column align="center" prop="产品名称" label="产品名称" width="190" />
        <el-table-column align="center" prop="计划数量订单" label="计划数量" width="80" />
        <el-table-column align="center" label="要求完工日" width="120">
          <template slot-scope="scope">{{ formatDate(scope.row.要求完工日期) }}</template>
        </el-table-column>
        <el-table-column align="center" prop="当前序" label="当前序" width="80" />
        <el-table-column align="center" label="排产" width="90">
          <template slot-scope="scope">
            <div class="status-light" :class="scope.row.排产状态 === 1 ? 'status-light-green' : 'status-light-gray'" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="开工" width="80">
          <template slot-scope="scope">
            <div class="status-light" :class="scope.row.开工时间 === 1 ? 'status-light-green' : 'status-light-gray'" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="终检" width="80">
          <template slot-scope="scope">
            <div class="status-light" :class="scope.row.终检 === '是' ? 'status-light-green' : 'status-light-gray'" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="加急" width="80">
          <template slot-scope="scope">
            <div class="status-light" :class="scope.row.加急状态 === '加急' ? 'status-light-green' : 'status-light-gray'" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="优先级" width="80">
          <template slot-scope="scope">
            <div class="status-light" :class="scope.row.优先级 === '是' ? 'status-light-green' : 'status-light-gray'" />
          </template>
        </el-table-column>
        <!-- <el-table-column  align="center" :label = "'工序1\n工序名称'" prop = "工序名称[0]" width="80"/>
        <el-table-column align="center" :label = "'工序1\n指派对象'" prop = "指派对象[0]" width="80"/>
        <el-table-column align="center" :label = "'工序1\n开始时间'" prop = "计划开始时间[0]" width="120"/>
        <el-table-column align="center" :label = "'工序1\n结束时间'" prop = "计划完成时间[0]" width="120"/>
        <el-table-column align="center" :label = "'工序1\n完成进度'" prop = "进度[0]" width="80"/>
        <el-table-column align="center" :label = "'工序2\n工序名称'" prop = "工序名称[1]" width="80"/>
        <el-table-column align="center" :label = "'工序2\n指派对象'" prop = "指派对象[1]" width="80"/>
        <el-table-column align="center" :label = "'工序2\n开始时间'" prop = "计划开始时间[1]" width="120"/>
        <el-table-column align="center" :label = "'工序2\n结束时间'" prop = "计划完成时间[1]" width="120"/>
        <el-table-column align="center" :label = "'工序2\n完成进度'" prop = "进度[1]" width="80"/>
        <el-table-column align="center" :label = "'工序3\n工序名称'" prop = "工序名称[2]" width="80"/>
        <el-table-column align="center" :label = "'工序3\n指派对象'" prop = "指派对象[2]" width="80"/>
        <el-table-column align="center" :label = "'工序3\n开始时间'" prop = "计划开始时间[2]" width="120"/>
        <el-table-column align="center" :label = "'工序3\n结束时间'" prop = "计划完成时间[2]" width="120"/>
        <el-table-column align="center" :label = "'工序3\n完成进度'" prop = "进度[2]" width="80"/>
        <el-table-column align="center" :label = "'工序4\n工序名称'" prop = "工序名称[3]" width="80"/>
        <el-table-column align="center" :label = "'工序4\n指派对象'" prop = "指派对象[3]" width="80"/>
        <el-table-column align="center" :label = "'工序4\n开始时间'" prop = "计划开始时间[3]" width="120"/>
        <el-table-column align="center" :label = "'工序4\n结束时间'" prop = "计划完成时间[3]" width="120"/>
        <el-table-column align="center" :label = "'工序4\n完成进度'" prop = "进度[3]" width="80"/>
        <el-table-column align="center" :label = "'工序5\n工序名称'" prop = "工序名称[4]" width="80"/>
        <el-table-column align="center" :label = "'工序5\n指派对象'" prop = "指派对象[4]" width="80"/>
        <el-table-column align="center" :label = "'工序5\n开始时间'" prop = "计划开始时间[4]" width="120"/>
        <el-table-column align="center" :label = "'工序5\n结束时间'" prop = "计划完成时间[4]" width="120"/>
        <el-table-column align="center" :label = "'工序5\n完成进度'" prop = "进度[4]" width="80"/> -->
        
      </el-table>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      orderNo: '',
      contractNo: '',
      productCode: '',
      productName: '',
      processName: '',
      nature: '',
      productionStatus: '全部',
      completionTime: [],
      loading: false,
      tableData: [],
      selectedRow: null,
      editDialogVisible: false,
      editSubmitLoading: false,
      currentRow: {},
      editForm: {
        优先级: '',
        未完成说明: '',
        派工特殊说明: ''
      },
      splitTaskDialogVisible: false,
      splitTaskSubmitLoading: false,
      stationOptions: [],
      splitTaskForm: {
        分配数量: 0,
        指派对象: '',
        指派对象编号: '',
        派工特殊备注: '',
        计划开始时间: '',
        计划结束时间: '',
        最晚开始时间: '',
        任务概述: ''
      },
      planStartTime: [],
      planendTime: [],
    }
  },
  created() {
    var now = new Date()
    var start = new Date(Date.UTC(now.getFullYear() - 2, now.getMonth(), now.getDate(), 0, 0, 0)).toISOString().replace('T', ' ').replace('.000Z', '')
    var end = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59)).toISOString().replace('T', ' ').replace('.000Z', '')
    this.searchTable()
  },
  methods: {
    getHeaderClass({ row, rowIndex }) {
      // row: 当前行的数据对象
      // rowIndex: 当前行的索引（从0开始）
      console.log(row)
      if (row.绿 == 1) {
        return 'warning-row'
      }else if (row.蓝 === 1) {
        return 'error-row';
      }else if (row.橙 === 1) {
        return 'success-row';
      }else{
        return '';
      }
        
      
    },
    formatDate(date) {
      if (!date) return ''
      return date.split(' ').length > 1 ? date.split(' ')[0] : date
    },
    mergeOrderData(dataList) {
      const orderMap = new Map();
      const opMap = new Map();
      dataList.forEach(item => {
        const orderNumber = item.订单号;
        if (!orderMap.has(orderNumber) ) {
          orderMap.set(orderNumber, {
            ...item,
            // 需要累加的字段
            // 指派数量: item.指派数量 || 0,
            // 工序计划数量: item.工序计划数量 || 0,
            // 计划数量: item.计划数量 || 0,
            // 需要循环的字段
            // 工序列表: [item.工序名称],
            // 指派对象列表: [item.指派对象],
            // 计划完成时间列表: [this.formatDate(item.计划完成时间)],
            // 计划开始时间列表: [this.formatDate(item.计划开始时间)],
            // 进度列表: [item.进度],
            当前序:'',
            开工时间:0,
            序检:item.序检,
            子数据:[{
              工序名称:item.工序名称,
              指派对象:item.指派对象,
              计划完成时间:item.计划完成时间,
              计划开始时间:item.计划开始时间,
              进度:item.进度,
              拆分内码:item.拆分内码,
              计划数量:item.计划数量,
              开工时间:item.开工时间,
              绿:0,
              橙:0,
              蓝:0,
            }]
          });
        } else {
          // 合并到现有项
          
          // 累加数值字段
          // existingItem.指派数量 += item.指派数量 || 0;
          // existingItem.工序计划数量 += item.工序计划数量 || 0;
          // existingItem.计划数量 += item.计划数量 || 0;
         
          const existingItem = orderMap.get(orderNumber);
          existingItem.子数据.push({
            工序名称:item.工序名称,
            指派对象:item.指派对象,
            计划完成时间:item.计划完成时间,
            计划开始时间:item.计划开始时间,
            进度:item.进度,
            拆分内码:item.拆分内码,
            计划数量:item.计划数量,
            开工时间:item.开工时间,
            绿:0,
            橙:0,
            蓝:0,
          })
          existingItem.子数据.forEach((element,index) => {
            if(new Date(element.开工时间) > new Date('1900-01-01 00:00:00')){
              element.绿 = 1
            }else{
              element.绿 = 0
            }
            if(element.进度 == 100){
              element.蓝 = 1
              element.绿 = 0
            }else{
              element.蓝 = 0
            }
            if(index>0){
              if(new Date(element.开工时间) == new Date('1900-01-01 00:00:00') & existingItem.子数据[index-1].进度 == 100){
                element.橙 = 1
                element.绿 = 0
              }else{
                element.橙 = 0
              }
            }
            
          });
          
          if(item.进度 < 100 & item.进度 > 0){
            existingItem.当前序 = item.工序名称
          }
          if(item.优先级 == '是' ){
            existingItem.优先级 = item.优先级
          }
          if(item.终检 == '是' ){
            existingItem.终检 = item.终检
          }
          if(new Date(item.开工时间) > new Date('1900-01-01 00:00:00')){
            existingItem.开工时间 = 1
          }
        }
      });
      
      this.tableData =  Array.from(orderMap.values()).map(item => ({
        // 基本信息
        订单号: item.订单号,
        合同号: item.合同号,
        产品编码:item.产品编码,
        产品名称:item.产品名称,
        计划数量订单:item.计划数量订单,
        要求完工日期:item.要求完工日期,
        排产状态:item.排产状态,
        优先级:item.优先级,
        当前序:item.当前序,
        计划数量: item.计划数量,
        开工时间: item.开工时间,
        序检:item.序检,
        子数据:item.子数据,
        加急状态:item.加急状态,
        终检:item.终检,
      }));
    }, 
    searchTable() {
      this.loading = true
      this.tableData = []
      var param = []
      param.push(['订单号', this.orderNo || 0])
      param.push(['物料类型', '自制件'])
      param.push(['合同号', this.contractNo])
      param.push(['产品编码', this.productCode])
      param.push(['产品名称', this.productName])
      param.push(['工序名称', this.processName])
      param.push(['计划开始1', this.planStartTime[0]])
      param.push(['计划开始2', this.planStartTime[1]])
      param.push(['计划完成1', this.planendTime[0]])
      param.push(['计划完成2', this.planendTime[1]])
      param.push(['要求完工日期1', this.completionTime ? this.completionTime[0] : ''])
      param.push(['要求完工日期2', this.completionTime ? this.completionTime[1] : ''])
      param.push(['排产状态', this.productionStatus])
      param.push(['指派对象', '全部'])
      var Data = this.CreateData('11', 'MES_OrderPlanned_Queryzp', param)
      this.ExecDatabase(Data).then(response => {
        this.loading = false
        if (response.data.length !== 0) {
          this.mergeOrderData(response.data)
        }
      }).catch(() => {
        this.loading = false
      })
    },
    handleRowClick(row) {
      this.selectedRow = row
    },
    editTask(row) {
      this.currentRow = row
      this.editForm = {
        优先级: row.优先级 || '',
        未完成说明: row.未完成说明 || '',
        派工特殊说明: row.派工特殊说明 || ''
      }
      this.editDialogVisible = true
    },
    submitEditForm() {
      this.editSubmitLoading = true
      const params = []
      params.push(['订单号', this.currentRow.订单号])
      params.push(['订单行号', this.currentRow.订单行号])
      params.push(['订单拆分内码', this.currentRow.拆分内码])
      params.push(['优先级', this.editForm.优先级])
      params.push(['未完成说明', this.editForm.未完成说明])
      params.push(['派工特殊说明', this.editForm.派工特殊说明])
      params.push(['最后编辑人', this.$store.state.user.name])

      const Data = this.CreateData('12', 'MES_OrderPlanned_DescriptionEdit', params)
      this.ExecDatabase(Data).then(() => {
        this.$message.success('保存成功')
        this.editDialogVisible = false
        this.searchTable()
      }).catch(() => {
        this.$message.error('保存失败')
      }).finally(() => {
        this.editSubmitLoading = false
      })
    },
    handleOutsourceNotify(row) {
      this.$confirm('确认同计划发起外协通知吗?', '确认', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning',
        center: true
      }).then(() => {
        this.$message.success('外协通知已发送')
      }).catch(() => {
      })
    },
    openSplitTask() {
      if (!this.selectedRow) {
        this.$message.warning('请先选择需要操作的行')
        return
      }
      this.getStationList()
      this.splitTaskForm = {
        分配数量: this.selectedRow.计划数量 || 0,
        指派对象: this.selectedRow.指派对象 || '',
        指派对象编号: this.selectedRow.指派对象编号 || '',
        派工特殊备注: this.selectedRow.派工特殊说明 || '',
        计划开始时间: this.selectedRow.计划开始时间 || '',
        计划结束时间: this.selectedRow.计划完成时间 || '',
        最晚开始时间: this.selectedRow.最晚开始时间 || '',
        任务概述: this.selectedRow.计划数量 || ''
      }
      this.splitTaskDialogVisible = true
    },
    submitSplitTaskForm() {
      this.splitTaskSubmitLoading = true
      this.$confirm('确认要拆分子任务吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 空逻辑
        this.splitTaskSubmitLoading = false
        this.splitTaskDialogVisible = false
        this.$message.success('操作成功')
        this.searchTable()
      }).catch(() => {
        this.splitTaskSubmitLoading = false
        this.$message.info('已取消操作')
      })
    },
    getStationList() {
      const params = []
      const Data = this.CreateData('11', 'Prog_MES_LoadStations', params)
      this.ExecDatabase(Data).then(response => {
        if (response.data && response.data.length > 0) {
          this.stationOptions = response.data.map(item => ({
            label: item.OPName,
            value: item.OPName,
            code: item.VisCode
          }))
        }
      })
    },
    handleStationChange(value) {
      const selected = this.stationOptions.find(item => item.value === value)
      if (selected) {
        this.splitTaskForm.指派对象编号 = selected.code
      }
    }
  }
}
</script>

<style scoped>

::v-deep .el-table th.el-table__cell>.cell{
  white-space: pre-wrap;
}
.process{
  width: 120px;
  display: inline-flex;
}
.search-container {
  margin-bottom: 20px;
}

.show-text {
  margin-right: 5px;
  line-height: 32px;
}

.status-light {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.status-light-green {
  background-color: #67C23A;
}

.status-light-gray {
  background-color: #909399;
}

.dialog-footer {
  text-align: right;
}
::v-deep .warning-row {
  background-color: #67c23a !important;
}

::v-deep .error-row {
  background-color: #409eff !important;
}

::v-deep .success-row {
  background-color: #f2a201 !important;
}
::v-deep .el-table td.el-table__cell{
  border: 0;
}
/* ::v-deep .el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: initial !important;
} */
</style>
