<template>
  <div class="ele-body">
    <el-form
      inline
      ref="formRef"
      :model="{ ...formData, pickOrderList }"
      :show-message="false"
      class="form-wrapper"
    >
      <el-card>
        <div class="page-title">
          <el-page-header @back="$router.go(-1)">
            <div slot="content" class="pageContent">
              <div>{{ title }}领料</div>
            </div>
          </el-page-header>
          <el-button type="primary" @click="handleReport">一键报工</el-button>
        </div>

        <header-title title="工单信息">
          <el-form-item label="执行人工号" required prop="executorId">
            <personSelectRemote
              v-model="formData.executorId"
              placeholder="请输入"
              @selfChange="(val, item) => (formData.executorName = item.name)"
            />
          </el-form-item>
          <el-form-item label="执行日期" prop="executorTime">
            <el-date-picker
              v-model="formData.executorTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              format="yyyy-MM-dd HH:mm"
              placeholder="请选择"
            ></el-date-picker>
          </el-form-item>
        </header-title>

        <ele-pro-table
          :needPage="false"
          :columns="orderColumns"
          :datasource="orderList"
          cache-key="picking-table"
        >
          <template v-slot:toolbar>
            <el-link type="primary" @click="addOrder">加入工单</el-link>
          </template>
          <template v-slot:action="{ $index }">
            <el-link type="danger" @click="delOrder($index)">删除</el-link>
          </template>
        </ele-pro-table>
        <header-title title="物料信息" class="mt-16"> </header-title>

        <ele-pro-table
          :columns="materialColumns"
          :datasource="pickOrderList"
          cache-key="picking-table-material"
        >
          <template v-slot:toolbar>
            <el-link type="primary" @click="addMaterial">添加物料</el-link>
          </template>
          <template v-slot:action="{ $index }">
            <el-link type="danger" @click="delMaterial($index)">删除</el-link>
          </template>
          <template v-slot:warehouse="{ row, $index }">
            <el-form-item
              label=""
              :prop="`pickOrderList.${$index}.warehouseId`"
              required
            >
              <DictSelection
                v-model="row.warehouseId"
                dict-name="仓库"
                @itemChange="(item) => (row.warehouse = item.dictValue)"
              ></DictSelection>
            </el-form-item>
          </template>
          <template v-slot:demandWeight="{ row, $index }">
            <el-form-item
              label=""
              :prop="`pickOrderList.${$index}.demandWeight`"
              required
            >
              <el-input-number
                class="w100"
                :controls="false"
                v-model="row.demandWeight"
                :min="0"
              ></el-input-number>
            </el-form-item>
          </template>
        </ele-pro-table>
      </el-card>
    </el-form>

    <orderDailog ref="orderDailogRef" @success="orderSuccess" />
    <ChooseMaterial ref="ChooseMaterialRef" @success="materialSuccess" />
  </div>
</template>

<script>
  // import Extrusion from './components/report/Extrusion';
  // import Drying from './components/report/Drying';
  // import Heating from './components/report/Heating';
  // import HalfAdded from './components/report/HalfAdded';
  // import Processing from './components/report/Processing';
  // import Package from './components/report/Package';
  // import Warehousing from './components/report/Warehousing';
  // import Sinter from './components/report/Sinter';
  // import Furnace from './components/report/Furnace';
  import orderDailog from './components/order-dailog';
  import ChooseMaterial from '@/components/material/ChooseMaterial';
  import { batchSave } from '@/api/produceOrder';
  import DictSelection from '@/components/Dict/DictSelection.vue';
  import personSelectRemote from '@/components/CommomSelect/person-select-remote';
  import { getRouteTabKey, removePageTab } from '@/utils/page-tab-util';
  export default {
    components: {
      personSelectRemote,
      orderDailog,
      ChooseMaterial,
      DictSelection
    },
    data () {
      return {
        descriptionsShow: true,
        activeName: '1',
        formData: {
          executorTime: '',
          executorName: '',
          executorId: ''
        },
        orderColumns: [
          {
            label: '工单号',
            prop: 'code'
          },
          {
            label: '产品编码',
            prop: 'productCode'
          },
          {
            label: '产品名称',
            prop: 'productName'
          },
          {
            label: '牌号',
            prop: 'brandNo'
          },
          {
            label: '型号',
            prop: 'model'
          },
          {
            label: '要求成型数量',
            prop: 'formingNum'
          },
          {
            label: '要求成型重量',
            prop: 'formingWeight'
          },
          {
            label: '未成型数量',
            formatter: (row) => {
              return row.formingNum - row.formedNum;
            }
          },
          {
            label: '未成型重量',
            formatter: (row) => {
              return row.formingWeight - row.formedWeight;
            }
          },
          {
            label: '计划开始时间',
            prop: 'planStartTime'
          },
          {
            label: '实际开始时间',
            prop: 'startTime'
          },
          {
            slot: 'action',
            label: '操作'
          }
        ],
        orderList: [],
        pickOrderList: [],
        materialColumns: [
          {
            label: '序号',
            type: 'index',
            width: 55
          },
          {
            label: '编码',
            prop: 'materialCode'
          },
          {
            label: '名称',
            prop: 'materialName'
          },
          {
            label: '类型',
            prop: 'materialTypeName'
          },
          {
            label: '单位',
            prop: 'unit'
          },
          {
            label: '牌号',
            prop: 'brandNo'
          },
          {
            label: '型号',
            prop: 'model'
          },
          {
            label: '规格',
            prop: 'specifications'
          },
          {
            slot: 'demandWeight',
            label: '需求数量'
          },
          {
            slot: 'warehouse',
            label: '仓库'
          },
          {
            slot: 'action',
            label: '操作'
          }
        ]
      };
    },
    computed: {
      title () {
        return this.$route.query.name;
      }
    },
    methods: {
      addOrder () {
        this.$refs.orderDailogRef.open(this.orderList.slice(0));
      },
      orderSuccess (list) {
        const obj = {};
        this.orderList = [...this.orderList, ...list].reduce((next, pre) => {
          if (!obj[pre.id]) {
            obj[pre.id] = true;

            next.push(pre);
          }
          return next;
        }, []);
      },
      addMaterial () {
        this.$refs.ChooseMaterialRef.open(this.pickOrderList.slice(0));
      },
      materialSuccess (list) {
        const obj = {};
        this.pickOrderList = [...this.pickOrderList, ...list].reduce(
          (next, pre) => {
            if (!obj[pre.id]) {
              obj[pre.id] = true;

              next.push({
                brandNo: pre.brandNum,
                // "executorId": pre.brandNo,
                // "executorName": pre.brandNo,
                // "executorTime": pre.brandNo,
                materialCode: pre.code,
                materialId: pre.id,
                materialName: pre.name,
                materialTypeName: pre.categoryLevelGroupName,
                materialType: +pre.categoryLevelId,
                model: pre.modelType,
                specifications: pre.specification,
                unit: pre.measuringUnit,
                warehouse: '',
                warehouseId: '',
                demandWeight: ''
              });
            }
            return next;
          },
          []
        );
      },
      delMaterial (index) {
        this.$confirm('是否删除', '提示')
          .then(() => {
            this.pickOrderList.splice(index, 1);
          })
          .catch(() => {});
      },
      delOrder (index) {
        this.$confirm('是否删除', '提示')
          .then(() => {
            this.orderList.splice(index, 1);
          })
          .catch(() => {});
      },
      async handleReport () {
        if (!this.pickOrderList?.length) {
          return this.$message.error('请添加物料');
        }
        this.$refs.formRef.validate(async (value) => {
          if (value) {
            await batchSave({
              ...this.formData,
              pickOrderList: this.pickOrderList
            });
            this.$message.success('提交成功！');
            const key = getRouteTabKey();
            this.$router.push('/produceOrder');
            removePageTab({ key });
          } else {
            this.$message.error('请添完善必填项');
          }
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .el-tabs {
    margin-top: 20px;
  }
  .el-button {
    margin-top: 10px;
  }
  .slideUp-icon {
    transform: rotate(-90deg);
  }
  .slideDown-icon {
    transform: rotate(90deg);
  }

  .form-wrapper {
    :deep(.el-form-item) {
      margin-bottom: 0;
    }
  }
</style>
