<template>
    <div>
      <el-form :model="tableForm" ref="tableForm" label-width="0px" class="demo-ruleForm">
        <el-table
        v-loading="loading"
        :data="tableForm.tableData"
      >
        <!-- <el-table-column type="selection" width="55" align="center"/> -->
        <el-table-column label="工序名称" width="120" prop="processName"/>
        <el-table-column label="工作中心" width="120" prop="workstationName"/>
        <el-table-column label="标准工时" width="100" prop="stdWorkingTime"/>
        <el-table-column label="工时单位" width="80" prop="stdWorkingTimeUom"/>
        <el-table-column label="工序总量" width="80" prop="quantity"/>
        <el-table-column label="工作单元" width="180" prop="workunitId">
          <template slot-scope="scope">
            <el-form-item :prop="'tableData.' + scope.$index + '.workunitId'"
                :rules="rules.workunitId">
              <el-select v-model="scope.row.workunitId" placeholder="请选择" @focus="handleFous(scope.row)" @change="e => changeWorkunit(e, scope.row)">
                <el-option
                  v-for="(item,index) in scope.row.taskList"
                  :key="index"
                  :label="item.workunitName"
                  :value="item.workunitId">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="计划开始时间" width="220" prop="scheduleStartTime">
          <template slot-scope="scope">
             <el-form-item :prop="'tableData.' + scope.$index + '.scheduleStartTime'"
                :rules="rules.scheduleStartTime">
                <el-date-picker
                v-model="scope.row.scheduleStartTime"
                type="datetime"
                style="width: 100%;"
                placeholder="请选择计划开始时间"
                format ="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="计划结束时间" width="220" prop="scheduleEndTime">
          <template slot-scope="scope">
            <el-form-item :prop="'tableData.' + scope.$index + '.scheduleEndTime'"
                :rules="rules.scheduleEndTime">
                <el-date-picker
                v-model="scope.row.scheduleEndTime"
                type="datetime"
                style="width: 100%;"
                placeholder="请选择计划结束时间"
                format ="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                @change="editTime(scope.row, 'end')"
                >
              </el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
      </el-form>
    </div>
</template>

<script>
import { getProWorkOrderProcessList, workorderProofMakeProduction, proofMakeProductionByWorkunit } from "@/api/mes/pro/workorder";
import { gettaskWorkunitList } from '@/api/mes/pro/scheduleList'

export default {
  name: "commandList",
  components: { },
  data() {
    return {
      showFlag: false,
      // 选中数组
      ids: [],
      selectedRows: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 物料产品表格数据
      itemList: [{}],
      loading: false,
      tableForm: {
        //附属条件表格
        tableData: []
      },
      rules: {
        workunitId: [
          {
            required: true,
            message: '请选择工作单元',
            trigger: ['change', 'blur']
          }
        ],
        scheduleStartTime: [
          {
            required: true,
            message: '请选择计划开始时间',
            trigger: ['change', 'blur']
          }
        ],
        scheduleEndTime: [
          {
            required: true,
            message: '请选择计划结束时间',
            trigger: ['change', 'blur']
          }
        ]
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        },
        selectableRange:
          new Date().getHours() + ':' + (new Date().getMinutes() + 1) + ':00' + ' - 23:59:59',
        }
    };
  },
  created() {

  },
  mounted() {
    this.getList();
  },
  methods: {
    changeWorkunit(e, row) {
      proofMakeProductionByWorkunit(e).then(res => {
        if (res.data) {
          row['scheduleStartTime'] = res.data.startDate
          row['scheduleEndTime'] = res.data.endDate
        }
      })
    },
    /** 查询物料编码列表 */
    getList() {
      this.loading = true;
      getProWorkOrderProcessList({
        workorderId: this.$attrs.workorderId
      }).then((response) => {
        this.tableForm.tableData = response.rows.map(item => {
          return {
            ...item,
            scheduleStartTime: this.$attrs.currentData.requestDate ? this.$attrs.currentData.requestDate : null,
            scheduleEndTime: this.$attrs.currentData.requestDate ? this.$attrs.currentData.requestDate : null
          }
        })
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.statusArr = ["ORCHESTRATED"]
      this.handleQuery();
    },
    async handleFous(row) {
      // if (row.taskList&&row.taskList.length) {
      //   return
      // }
      const response = await gettaskWorkunitList({workstationId: row.workstationId})
      this.$set(row,'taskList',response.rows)
      console.log(row)
    },
    validateKey(rule, value, callback) {
      if (value === '') {
        callback(new Error('请选择类型'))
      } else {
        callback()
      }
    },
    submit(tableData) {
      // console.log(tableData)
      this.$refs.tableForm.validate(async(valid) => {
        if (valid) {
		      let params = {
            workorderId: this.$attrs.workorderId
          }
          let flag = false;
          params.processData = this.tableForm.tableData.map(item => {
            const startTime = new Date(item.scheduleStartTime).getTime() + 3 * 60 * 1000;
            const endTime = new Date(item.scheduleEndTime).getTime() + 3 * 60 * 1000;
            const nowTime = new Date().getTime();
            if(startTime < nowTime || endTime < nowTime) {
              flag = true;
            }
            return {
              "scheduleEndTime": item.scheduleEndTime,
              "scheduleStartTime": item.scheduleStartTime,
              "workorderProcessId": item.workorderProcessId,
              "workunitId": item.workunitId
            }
          })
          // console.log(params)
          if(flag) {
            return this.$message.warning('手工排产时间不得早于当前时间!');
          }
          workorderProofMakeProduction(params).then(res => {
            if (res.code === 200) {
              this.$emit('close')
              return true
            } else {
              this.$message.warning(res.msg)
            }
          })
        }
      })
    },
    editTime(row){
      const startTime = new Date(row.scheduleStartTime).getTime();
      const endTime = new Date(row.scheduleEndTime).getTime();
      if(startTime > endTime) {
        return this.$message.warning('计划结束时间不能小于计划开始时间!');
      }
    }
  },
};
</script>
