<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="primary" plain size="small">删除</el-button> -->
      <div class="items">
        <span class="label">累计工单条数</span>
        {{ tableData.length }}条
      </div>
      <div class="items">
        <span class="label">累计成型数量</span>
        {{ sumData.formingNum }}pcs
      </div>
      <div class="items">
        <span class="label">累计成型重量</span>
        {{ sumData.formingWeight }}{{ infoData.productUnitWeight }}
      </div>
      <div class="items">
        <span class="label">设备数量</span>
        14条
      </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="">
          <template v-slot="{ row, $index }">
            <el-form-item
              :prop="`tableData.${$index}.formingNum`"
              :rules="rule.formingNum"
            >
              <el-input
                type="number"
                v-model.number="row.formingNum"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="成型重量" prop="">
          <template v-slot="{ row, $index }">
            <el-form-item
              :prop="`tableData.${$index}.formingWeight`"
              :rules="rule.formingWeight"
            >
              <el-input
                type="number"
                v-model.number="row.formingWeight"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="开始日期" prop="">
          <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"
                :disabledDate="() => time.getTime() >= row.planCompleteDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="班次" prop="">
          <template v-slot="{ row, $index }">
            <el-form-item
              :prop="`tableData.${$index}.classeId`"
              :rules="rule.classeId"
            >
              <classesSelect
                v-model="row.classeId"
                @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">
          <template v-slot="{ row, $index }">
            <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, $index }">
            <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 './equipment-dailog.vue';
  import classesSelect from '@/components/CommomSelect/classes-select';
  import { getExector } from '@/api/workforceManagement/classes';

  import { release } from '@/api/productionPlan/order.js';
  import { getCode } from '@/api/codeManagement';
  export default {
    components: { equipmentDailog, classesSelect },
    props: {
      infoData: {
        type: Object,
        default: () => ({})
      },
      orderList: {
        type: Array,
        default: () => []
      }
    },
    data () {
      return {
        tableData: [],
        rule: {
          formingNum: [
            { required: true, message: '请输入成型数量', trigger: 'blur' }
          ],
          formingWeight: [
            { required: true, message: '请输入成型重量', trigger: 'blur' }
          ],
          planStartTime: [
            { required: true, message: '请选择开始日期', trigger: 'blur' }
          ],
          classeId: [
            { 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 }]
          }
        ]
      };
    },
    computed: {
      sumData () {
        let formingNum = 0;
        let formingWeight = 0;
        this.tableData.forEach((ele) => {
          formingNum += ele.formingNum || 0;
          formingWeight += ele.formingWeight || 0;
        });

        return { formingNum, formingWeight };
      }
    },
    watch: {
      orderList: {
        immediate: true,
        handler () {
          if (this.orderList?.length) {
            this.tableData = this.orderList;
          }
        }
      }
    },
    methods: {
      // 发布
      handleRelease () {
        this.$refs.formRef.validate((value) => {
          if (value) {
            this.$confirm('发布工单后不可撤回，确定发布吗？', '发布确认').then(
              async () => {
                await release(this.tableData);

                this.$message.success('发布成功！');
                this.$router.go(-1);
              }
            );
          }
        });
      },
      // 班次改变选择执行人
      async handleClasseChange (val, row) {
        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 () {
        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');
          // classeId	班次id		false
          // classeName	班次名称		false
          // code	工单号		false
          // deviceCode	设备编码		false
          // deviceId	设备id		false
          // deviceName	设备名称		false
          // executorId	执行人id		false
          // executorName	执行人名称		false
          // formingNum	成型数量		false
          // generativeRules	生成规则		false
          // planCompleteTime	计划完成时间		false
          // planStartTime	计划开始时间		false
          // productionPlanCode	生产计划号		false
          // productionPlanId	生产计划id		false
          // workOrderType	工单类型
          this.tableData.push({
            classeId: pre.classeId,
            code: code,
            deviceCode: pre.code,
            deviceId: pre.id,
            deviceName: pre.name,
            executorId: '',
            executorName: '',
            planCompleteTime: '', //当班下班时间,
            planStartTime: pre.planCompleteDate,
            planCompleteDate: pre.planCompleteDate,
            formingNum: pre.formingNum,
            formingWeight: '',
            productionPlanId: this.infoData.id,
            productionPlanCode: this.infoData.code,
            produceVersionId: this.infoData.produceVersionId
          });
        }
      },
      handleDelete (index) {
        this.tableData.splice(index, 1);
      }
    }
  };
</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>
