<template>
  <div class="plan-view">
    <div class="description">
      <div class="label"></div>
      <!-- <div class="label">方案说明</div>
      <div class="content">
        <template v-for="(item, index) in rulesList">
          <template v-for="(itm, idx) in item.list">
            <template v-if="!itm.lastDisabled">
              <div class="tag" :key="index + '' + idx">{{ itm.label }}</div>
            </template>
          </template>
        </template>
      </div> -->
      <div class="operate">
        <el-button type="primary" plain @click="handleRelease"
          >发布当前方案</el-button
        >
        <!-- <el-button type="primary">保存</el-button> -->
      </div>
    </div>

    <div class="display-box">
      <el-button type="primary" plain size="small" @click="addOrder"
        >添加工单</el-button
      >
      <!-- <el-button type="danger" plain size="small" @click="remove">删除</el-button> -->
      <div class="items">
        <span class="label">累计工单条数</span>
        {{ tableData.length }}条
      </div>
      <div class="items">
        <span class="label">累计生产重量</span>
        {{ sumData.productNum }}{{ infoData.unit }}
      </div>
      <div class="items">
        <span class="label">设备数量</span>
        {{ sumData.equipment }}台
      </div>
      <!-- <div class="items">
        <span class="label">生产剂需求</span>
        14条
      </div>
      <div class="items">
        <span class="label">混合料需求</span>
        14条
      </div> -->
    </div>
    <el-form :model="{ tableData }" label-width="0" ref="formRef">
      <el-table :data="tableData">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column label="工单号" prop="code"></el-table-column>
        <el-table-column label="生产重量" prop="" width="120">
          <template v-slot="{ row, $index }">
            <el-form-item
              :prop="`tableData.${$index}.productNum`"
              :rules="rule.productNum"
            >
              <el-input
                type="number"
                v-model.number="row.productNum"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="开始日期" prop="" width="160">
          <template v-slot="{ row, $index }">
            <el-form-item
              :prop="`tableData.${$index}.planStartTime`"
              :rules="rule.planStartTime"
            >
              <el-date-picker
                class="w100"
                :clearable="false"
                v-model="row.planStartTime"
                :pickerOptions="{
                  disabledDate: (time) =>
                    (row.planCompleteDate
                      ? time.getTime() >=
                        new Date(
                          new Date(row.planCompleteDate).setHours(0, 0, 0, 0)
                        ).getTime()
                      : true) &&
                    time.getTime() <
                      new Date(new Date().setHours(0, 0, 0, 0)).getTime()
                }"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="班次" prop="" width="160">
          <template v-slot="{ row, $index }">
            <el-form-item
              :prop="`tableData.${$index}.classesId`"
              :rules="rule.classesId"
            >
              <classesSelect
                ref="classesSelectRef"
                :init="false"
                v-model="row.classesId"
                @selfChange="(val) => handleClasseChange(val, row)"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="设备编码" prop="deviceCode"></el-table-column>
        <el-table-column label="设备名称" prop="deviceName" width="160">
          <template v-slot="{ row}">
            <el-input
              :value="row.deviceName"
              @click.native="editOrder(row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="可执行人"
          prop="executorName"
          min-width="220px"
          show-overflow-tooltip
        >
          <template v-slot="{ row }">
            <template v-if="row.executorName.length">
              <el-tag
                type="success"
                v-for="(item, index) in row.executorName.split(',')"
                :key="index"
                >{{ item }}</el-tag
              >
            </template>
          </template></el-table-column
        >
        <el-table-column label="操作" prop="">
          <template v-slot="{ $index }">
            <el-link type="danger" @click="handleDelete($index)">删除</el-link>
          </template>
        </el-table-column>
        <!-- <el-table-column type="selection"></el-table-column> -->
      </el-table>
    </el-form>
    <equipmentDailog
      ref="equipmentDailogRef"
      @success="equipmentSelect"
      :produceVersionId="infoData.produceVersionId"
    />
  </div>
</template>

<script>
  import equipmentDailog from '@/components/CreatePlan/equipment-dailog.vue';
  import classesSelect from '@/components/CommomSelect/classes-select';
  import { getExector } from '@/api/workforceManagement/classes';

  import { release } from '@/api/materialPlan/order.js';
  import { getCode } from '@/api/codeManagement';
  import { getRouteTabKey, removePageTab } from '@/utils/page-tab-util';
  import { deepClone } from '@/utils';
  export default {
    components: { equipmentDailog, classesSelect },
    props: {
      infoData: {
        type: Object,
        default: () => ({})
      },
      orderList: {
        type: Array,
        default: () => []
      }
    },
    data () {
      return {
        deleteList: [], //已保存删除项
        tableData: [],
        rule: {
          productNum: [
            { required: true, message: '请输入生产数量', trigger: 'blur' }
          ],
          planStartTime: [
            { required: true, message: '请选择开始日期', trigger: 'blur' }
          ],
          classesId: [
            { required: true, message: '请选择班次', trigger: 'change' }
          ]
        },
        rulesList: [
          {
            type: 'radio',
            value: '',
            list: [
              { label: '多设备优先', value: 0 },
              { label: '多班次优先', value: 1 }
            ]
          },
          {
            type: 'checked',
            value: [],

            list: [
              { label: '设备产能优先', value: 0 },
              { label: '最早开始时间优先', value: 1 },
              { label: '开始时间优先', value: 2, lastDisabled: true }
            ]
          },
          {
            type: 'checked',
            value: [],
            list: [
              { label: '非空闲设备可用', value: 0 },
              { label: '检修设备可用', value: 1 },
              { label: '检修设备优先', value: 1, lastDisabled: true }
            ]
          },
          {
            type: 'radio',
            value: '',
            list: [{ label: '末单均衡', value: 0 }]
          }
        ],
        selectionList: []
      };
    },
    computed: {
      sumData () {
        let productNum = 0;
        let equi = new Set();
        this.tableData.forEach((ele) => {
          productNum += +ele.productNum || 0;

          equi.add(ele.deviceId);
        });

        return {
          productNum,
          equipment: equi.size
        };
      }
    },
    watch: {
      tableData: {
        immediate: true,
        handler () {
          this.$nextTick(() => {
            this.$refs.classesSelectRef &&
              this.$refs.classesSelectRef.getList();
          });
        }
      },
      orderList: {
        immediate: true,
        handler () {
          if (this.orderList?.length) {
            this.tableData = deepClone(this.orderList);
          }
        }
      }
    },
    methods: {
      back () {
        const key = getRouteTabKey();
        this.$router.push('/productionPlan');
        removePageTab({ key });
      },
      // chooseItem(selection){
      //  this.selectionList = selection
      // },
      // 发布
      handleRelease () {
        this.$refs.formRef.validate((value) => {
          if (value) {
            this.$confirm('发布工单后不可撤回，确定发布吗？', '发布确认')
              .then(async () => {
                const loading = this.$loading({
                  lock: true,
                  fullscreen: true,
                  text: '工单发布中...'
                });
                try {
                  // 反显对象会报错 status
                  const data = await release([
                    ...this.tableData.map((i) =>
                      Object.assign({}, i, {
                        status: 4,
                        model: this.infoData.model,
                        brandNo: this.infoData.brandNo
                      })
                    ),
                    ...this.deleteList
                  ]);
                  if (data) {
                    this.$message.success('发布成功！');
                  } else {
                    this.$message.error('发布失败，请重新发布！');
                  }
                  this.back();
                } catch (error) {
                  console.error(error);
                }
                loading.close();
              })
              .catch(() => {});
          }
        });
      },
      // 班次改变选择执行人
      async handleClasseChange (val, row) {
        if (!val) {
          row.executorId = '';
          row.executorName = '';
        }
        const res = await getExector(val);

        let executorId = '';
        let executorName = '';
        res.forEach((item) => {
          executorId += ',' + item.userVOList.map((itm) => itm.id).join(',');
          executorName +=
            ',' + item.userVOList.map((itm) => itm.name).join(',');
        });

        row.executorId = executorId.substring(1);
        row.executorName = executorName.substring(1);
      },
      addOrder () {
        if (this.tableData.length > 0)
          return this.$message.warning('工单只能添加一条！');
        this.$refs.equipmentDailogRef.open();
      },
      editOrder (row) {
        this.$refs.equipmentDailogRef.openSingle([row], (current) => {
          row.deviceCode = current.code;
          row.deviceId = current.id;
          row.deviceName = current.name;
          row.planStartTime = current.planCompleteDate;
          row.planCompleteDate = current.planCompleteDate;
        });
      },
      async equipmentSelect (list) {
        for (const pre of list) {
          const code = await getCode('product_order_code');
          // classesId	班次id		false
          // classeName	班次名称		false
          // code	工单号		false
          // deviceCode	设备编码		false
          // deviceId	设备id		false
          // deviceName	设备名称		false
          // executorId	执行人id		false
          // executorName	执行人名称		false
          // generativeRules	生成规则		false
          // planCompleteTime	计划完成时间		false
          // planStartTime	计划开始时间		false
          // batchingPlanId	生产计划号		false
          // batchingPlanCode	生产计划id		false
          // workOrderType	工单类型
          this.tableData.push({
            classesId: pre.classesId,
            code: code,
            deviceCode: pre.code,
            deviceId: pre.id,
            deviceName: pre.name,
            executorId: '',
            executorName: '',
            planCompleteTime: '', //当班下班时间,
            planStartTime: pre.planCompleteDate,
            planCompleteDate: pre.planCompleteDate,
            batchingPlanId: this.infoData.id,
            batchingPlanCode: this.infoData.code,
            produceVersionId: this.infoData.produceVersionId
          });
        }
      },
      handleDelete (index) {
        this.$confirm('确定删除当前数据？', '提示')
          .then(() => {
            const [item] = this.tableData.splice(index, 1);

            if (this.orderList.find((i) => i.id == item.id)) {
              item.deleted = 1;
              this.deleteList.push(item);
            }
          })
          .catch(() => {});
      }
    }
  };
</script>

<style lang="scss" scoped>
  .plan-view {
    ::v-deep(.el-form-item) {
      margin-top: 16px;
      margin-bottom: 16px;
    }
  }
  .description {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 20px;
    border: 1px solid rgba(215, 215, 215, 1);
    background-color: rgba(242, 242, 242, 1);
    .label {
      margin-right: 20px;
    }
    .content {
      flex: 1;
      display: flex;
      justify-content: flex-start;
      align-items: center;

      .tag {
        padding: 5px 10px;
        background-color: rgba(202, 249, 130, 1);
        border-radius: 20px;

        & + .tag {
          margin-left: 10px;
        }
      }
    }
  }

  .display-box {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: 10px;

    .items {
      margin-left: 30px;
      .label {
        font-weight: bold;
      }
    }
  }
</style>
