<template>
  <div class="content-height p20">
    <el-form :model="formData" ref="formRef" :rules="rules" label-width="110px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="名称" prop="name">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="审核部门" prop="auditDeptName">
            <selectTree
              ref="tree"
              class="w100"
              :clearable="false"
              :options="deptList"
              size="small"
              :props="{
                value: 'code',
                label: 'name',
                children: 'children'
              }"
              @getValue="auditorDeptClick"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="审核人" prop="auditId">
            <el-select
              filterable
              class="form-ipt"
              size="small"
              style="width: 100%"
              v-model="formData.auditId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in auditorList"
                :key="item.userId"
                :label="item.trueName"
                :value="item.userId"
                @click.native="() => (formData.auditName = item.trueName)"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="报损报溢部门" prop="reportDeptName">
            <el-input
              placeholder="自动带出"
              v-model="formData.reportDeptName"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="报损报溢人" prop="reportName">
            <el-input
              placeholder="自动带出"
              v-model="formData.reportName"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="盘点工单号" prop="workOrderCode">
            <el-input
              placeholder="自动带出"
              v-model="formData.workOrderCode"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="">
            <div class="type-box">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="handleAdd"
                >添加</el-button
              >
            </div>
            <el-table
              :data="formData.list"
              border
              style="width: 100%"
              :header-cell-style="{
                background: '#F0F3F3',
                border: 'none'
              }"
            >
              <el-table-column :label="`${assetName}编码`" prop="code">
              </el-table-column>
              <el-table-column :label="`${assetName}名称`" prop="name">
              </el-table-column>
              <el-table-column label="类型" prop="assetTypeDict.descp">
                <template slot-scope="{ row }">
                  {{ getDictValue('类型用途', row.assetTypeDict) }}
                </template>
              </el-table-column>
              <el-table-column label="批次号" prop="batch"> </el-table-column>
              <el-table-column
                v-for="(item, index) in tableHeader"
                :key="index"
                :label="item.label"
                :prop="item.prop"
              >
                <template slot-scope="{ row }">
                  <template v-if="item.formatter">
                    {{ item.formatter(row) }}
                  </template>
                  <template v-else>
                    {{ row[item.prop] }}
                  </template>
                </template>
              </el-table-column>
              <el-table-column
                label="单价"
                prop="univalence"
                width="150"
                align="center"
              >
                <template slot-scope="{ row, $index }">
                  {{ row.univalence
                  }}{{ { yuan: '元', wanyuan: '万元' }[row.univalenceUnit] }}
                </template>
              </el-table-column>
              <el-table-column label="最小单元" prop="minimumUnit">
                <template slot-scope="{ row }">
                  {{ row.unit }}/{{ row.minPackUnit }}
                </template>
              </el-table-column>
              <el-table-column label="盈/亏/损" prop="">
                <template slot-scope="{ row }">
                  <span :style="{ color: getEquStatus(row.status).color }">
                    {{ getEquStatus(row.status).label }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="数量" prop="amount">
                <template slot-scope="{ row }">
                  <span :style="{ color: getEquStatus(row.status).color }">
                    {{
                      ([1, 2].includes(row.status) ? '-' : '+') +
                      (row.checkNum || 0)
                    }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="货位信息" prop="goodsAllocation">
                <template slot-scope="{ row }">
                  {{ row.warehouseName }}-{{ row.reservoirName }}-{{
                    row.goodsShelfName
                  }}-{{ row.goodsAllocationName }}
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="{ row, $index }">
                  <el-link type="primary" @click="deleteRow($index)"
                    >删除</el-link
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
        <el-col :span="24" prop="remark">
          <el-form-item label="备注">
            <el-input
              v-model="formData.remark"
              type="textarea"
              placeholder="请详细说明"
              :rows="4"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="center mt20">
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button @click="$router.go(-1)">返回</el-button>
    </div>
    <WorkOrderSelectedDialog ref="workOrderRef" @success="workOrderConfirm" />
  </div>
</template>

<script>
  import { warehousingType } from '@/utils/dict/index';
  // import { save, getDetail } from '@/api/stockManagement/reportLoss.js'
  // import { warehouseListValuable } from '@/api/stockManagement/warehouseDefinition'
  import { wh_equStatus } from '@/utils/dict/warehouse';
  import { useDict, useDictLabel } from '@/utils/dict/index';
  // import org from '@/api/main/org'
  // import user from '@/api/main/user'
  import selectTree from '@/components/selectTree';
  import WorkOrderSelectedDialog from './components/WorkOrderSelectedDialog';
  // import { getAbnormaldetailList } from '@/api/workspace/workOrder'
  import dictMixin from '@/mixins/dictMixins';
  export default {
    components: { selectTree, WorkOrderSelectedDialog },
    mixins: [dictMixin],
    data() {
      return {
        getWarehousingType: useDictLabel(warehousingType),
        tableData: [],
        formData: {
          reportDeptId: '',
          reportDeptName: '',
          reportId: '',
          reportName: '',
          auditId: '',
          auditName: '',
          auditDeptId: '',
          auditDeptName: '',
          workOrderCode: '',
          type: '',
          list: []
        },
        rules: {
          // name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
        },
        deptList: [], //部门集合
        auditorList: [], //角色集合
        warehouseList: [] //仓库集合
      };
    },
    created() {
      // this.init()
      // this.requestDict('类型用途')
    },
    computed: {
      assetName() {
        if (this.formData.list?.length) {
          return this.getWarehousingType(this.formData.list[0].assetTypeDict);
        }
        return '';
      },
      tableHeader() {
        if (this.formData.list?.length) {
          return this.getTableHeader(this.formData.list[0].assetTypeDict);
        }
        return [];
      }
    },
    methods: {
      getTableHeader(selectEquiType) {
        switch (+selectEquiType) {
          case 3:
            return [{ label: '牌号', prop: 'assetBrand' }];
          case 8:
            return [
              { label: '型号', prop: 'assetSku' },
              { label: '规格', prop: 'specification' }
            ];
          case 4:
            return [
              { label: '牌号', prop: 'assetBrand' },
              { label: '型号', prop: 'assetSku' }
            ];
          case 5: //'周转车'
            return [
              { label: '规格', prop: 'specification' },
              {
                label: '材质',
                prop: 'texture',
                formatter(row) {
                  if (!row?.extendField) return '';
                  const extendField = JSON.parse(row.extendField);
                  return extendField.texture;
                }
              },
              {
                label: '长宽高',
                prop: '',
                formatter(row) {
                  if (!row?.extendField) return '';
                  const extendField = JSON.parse(row.extendField);
                  return `${extendField.length || '-'}*${
                    extendField.width || '-'
                  }*${extendField.high || '-'}`;
                }
              }
            ];
          case 2: //'舟皿'
            return [
              { label: '规格', prop: 'specification' },
              { label: '型号', prop: 'assetSku' },
              {
                label: '长宽高',
                prop: '',
                formatter(row) {
                  if (!row?.extendField) return '';
                  const extendField = JSON.parse(row.extendField);
                  return `${extendField.length || '-'}*${
                    extendField.width || '-'
                  }*${extendField.high || '-'}`;
                }
              }
            ];
          case 1: //'设备'
            return [
              { label: '型号', prop: 'assetSku' },
              { label: '规格', prop: 'specification' }
            ];
          case 6: //'模具'
            return [
              { label: '牌号', prop: 'assetBrand' },
              { label: '型号', prop: 'assetSku' },
              {
                label: '收缩系数',
                prop: '',
                formatter(row) {
                  if (!row?.extendField) return '';
                  const extendField = JSON.parse(row.extendField);
                  return extendField.shrinkageCoefficient;
                }
              }
            ];
          case 7: //'备品备件'
            return [
              { label: '规格', prop: 'specification' },
              { label: '型号', prop: 'assetSku' }
            ];
        }

        return [];
      },

      getEquStatus: useDict(wh_equStatus),
      async init() {
        if (this.$route.query.id) {
          this._getDetail(this.$route.query.id);
        } else {
          let obj = localStorage.getItem('orgInfo')
            ? JSON.parse(localStorage.getItem('orgInfo'))
            : {};
          this.formData.reportName = obj.name;
          this.formData.reportId = obj.id;
          this.formData.reportDeptName = obj.dept.name;
          this.formData.reportDeptId = obj.dept.code;
        }

        let tree = await org.tree();
        this.deptList = tree.data;
      },
      async _getWarehouse() {
        const res = await warehouseListValuable();
        if (res?.success) {
          this.warehouseList = res.data.filter((i) => !!i.status);
        }
      },
      async _getDetail(id) {
        const res = await getDetail({ id });
        if (res?.success) {
          this.formData = res.data;
        }
      },
      // 删除工单
      deleteRow(index) {
        this.formData.list.splice(index, 1);
      },
      // 选中工单
      async workOrderConfirm(data) {
        this.formData.workOrderCode = data.workOrderCode;

        const res = await getAbnormaldetailList({ workOrderId: data.id });
        if (res?.success) {
          this.formData.list = (res.data || []).map((itm) => {
            delete itm.id;
            if ([1, 2].includes(itm.equStatus)) {
              itm.checkNum = 1;
            }
            return {
              ...itm,
              amount: itm.checkNum,
              model: itm.assetSku,
              name: itm.assetName,
              productType: itm.assetTypeDict,
              code: itm.assetCode,
              batch: itm.batchNo,
              num: itm.bucketNum,
              bizTypeId: itm.bizTypeId,
              bizTypeName: itm.bizTypeName,
              status: itm.equStatus,
              unitPrice: itm.univalence,
              minimumUnit: itm.minPackUnit
            };
          });
        }
      },
      handleAdd() {
        this.$refs.workOrderRef.open();
      },
      // 审核部门 点击事件
      async auditorDeptClick(data) {
        this.formData.auditDeptId = data?.code;
        this.formData.auditDeptName = data?.name;
        this.formData.auditId = '';
        this.formData.auditName = '';

        this.$refs.formRef.validateField('auditDeptName');
        if (data) {
          this._getauditorList(data.code).then((res) => {
            if (data.code === this.formData.auditDeptId) {
              this.auditorList = res;
            }
          });
        }
      },
      _getauditorList(deptCode) {
        return new Promise(async (resolve) => {
          let res = await user.list({ deptCode, size: 9999 });
          if (res?.success) {
            resolve(res.data.items);
          }
        });
      },

      handleSave() {
        this.$refs.formRef.validate(async (value) => {
          if (value) {
            if (!this.formData.list.length) {
              this.$message.error('请选择工单！');
              return;
            }

            console.log(this.formData);
            const res = await save(this.formData);
            if (res?.success) {
              this.$message.success('提交成功！');
              this.$router.back();
            }
          } else {
            this.$message.error('请完善必填信息！');
          }
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .content-height {
    height: auto;
    background: #fff;
  }
  .p20 {
    padding: 20px;
  }
  .el-select,
  .el-date-editor {
    width: 100%;
  }
  .el-form-item {
    margin-bottom: 22px;
  }
  .material {
    margin-top: 20px;
    .flex {
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      .red {
        color: #ff4949;
      }
    }
  }
  .type-box {
    display: flex;
    justify-content: space-between;
    padding: 10px 0;
  }
  .flex {
    display: flex;
  }
  .mt10 {
    margin-top: 10px;
  }
  .mt20 {
    margin-top: 20px;
  }
  .center {
    text-align: center;
  }
  .area {
    justify-content: space-around;
  }
  .blue {
    background-color: #1989fa;
  }
  .green {
    background-color: #157a2c;
  }
  .grey {
    background-color: #aaa;
  }
  .red {
    background-color: red;
  }
  .areaContent {
    width: 45px;
    height: 45px;
    line-height: 45px;
    color: #fff;
    font-size: 14px;
    text-align: center;
    margin-right: 5px;
  }
  .mb10 {
    margin-bottom: 5px;
  }
  .out {
    background-color: #f2f2f2;
    color: #999;
    font-size: 14px;
    margin-right: 5px;
    width: 49px;
    padding: 0 18px;
    display: flex;
    align-items: center;
  }
  .minTitle {
    margin-bottom: 10px;
    font-size: 14px;
    color: #999;
  }
  .detailsTable {
    align-items: top;
    p {
      font-size: 14px;
      width: 110px;
      margin-right: 20px;
      text-align: right;
    }
  }
</style>
