<template>
  <div class="basicInformation">
    <el-form
      :model="formData"
      ref="formName"
      label-width="110px"
      :rules="rules"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="出库场景" prop="bizType">
            <el-select
              filterable
              placeholder="请选择"
              v-model="formData.bizType"
              clearable
              @change="handleBizSceneChange"
            >
              <el-option
                v-for="item in outputSceneState"
                :key="item.code"
                :value="item.code + ''"
                :label="item.label"
              ></el-option>
            </el-select> </el-form-item
        ></el-col>
        <el-col :span="8">
          <el-form-item
            :label="
              formData.bizType == 3
                ? '销售发货单'
                : formData.bizType == 4
                ? '领料单'
                : formData.bizType == 1
                ? '采购退货单'
                : '来源单据'
            "
            prop="sourceBizNo"
            v-if="formData.extInfo.assetType == 7 && formData.bizType == 4"
          >
            <!-- :disabled="!!(formData.sourceBizNo && warehousingMaterialList.length)" -->
            <el-select
              filterable
              v-model="formData.sourceBizNo"
              :disabled="!!formData.sourceBizNo"
              clearable
              placeholder="请输入"
              @change="handleDocumentSourceChange"
            >
              <el-option
                v-for="item in options"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option> </el-select
          ></el-form-item>
          <el-form-item
            :label="
              formData.bizType == 3
                ? '销售发货单'
                : formData.bizType == 4
                ? '领料单'
                : formData.bizType == 1
                ? '采购退货单'
                : '来源单据'
            "
            v-else
            prop="sourceBizNo"
          >
            <el-input
              @input="$forceUpdate()"
              placeholder="请输入"
              @change="handleDocumentSourceChange"
              v-model="formData.sourceBizNo"
              @click.native="
                formData.bizType == 4
                  ? handlePickorder()
                  : formData.bizType == 3
                  ? handleEom()
                  : null
              "
            >
              <el-button
                v-if="formData.bizType == 4 || formData.bizType == 3"
                slot="append"
                icon="el-icon-circle-close"
                @click.stop="onClear"
              ></el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出库物品类型" prop="extInfo.assetType">
            <!-- :isBindPlan="!!(warehousingMaterialList && warehousingMaterialList.length)" -->
            <selectTree
              ref="trees"
              class="form-ipt"
              size="medium"
              style="width: 100%"
              clearable
              :options="codeList"
              :props="{
                value: 'id',
                label: 'name',
                children: 'children'
              }"
              @getValue="assetTypeChange"
              :isAll="false"
            />
          </el-form-item>
        </el-col>

        <el-col :span="8" v-if="formData.bizType == 3">
          <el-form-item label="客户名称">
            <el-input
              placeholder="客户名称"
              disabled
              v-model="formData.clientName"
              clearable /></el-form-item
        ></el-col>
        <el-col :span="8" v-if="formData.bizType == 3">
          <el-form-item label="客户联系人">
            <el-input
              placeholder="客户联系人"
              disabled
              v-model="formData.clientUser"
              clearable /></el-form-item
        ></el-col>
        <el-col :span="8" v-if="formData.bizType == 3">
          <el-form-item label="客户电话">
            <el-input
              placeholder="客户电话"
              disabled
              v-model="formData.clientPhone"
              clearable /></el-form-item
        ></el-col>

        <el-col :span="8">
          <el-form-item label="权属部门" prop="deptName">
            <el-input
              placeholder="权属部门"
              disabled
              v-model="formData.extInfo.deptName"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出库登记人">
            <el-input
              placeholder="登记人"
              disabled
              v-model="formData.extInfo.createUserName"
              clearable /></el-form-item
        ></el-col>
        <el-col :span="8">
          <el-form-item label="领料人部门" prop="verifyDeptName">
            <selectTree
              ref="tree"
              class="form-ipt"
              size="medium"
              style="width: 100%"
              clearable
              :options="treeList"
              :props="{
                value: 'code',
                label: 'name',
                children: 'children'
              }"
              @getValue="auditorDeptClick"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="领料人" prop="fromUser">
            <el-select
              v-model="formData.fromUser"
              filterable
              placeholder="请选择领料人"
            >
              <el-option
                v-for="item in llrLsit"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                @click.native="
                  () => (formData.extInfo.fromUserPhone = item.phone)
                "
              >
              </el-option>
            </el-select> </el-form-item
        ></el-col>
        <el-col :span="8">
          <el-form-item label="领料人联系方式" prop="fromUserPhone">
            <el-input
              placeholder="请输入"
              disabled
              v-model="formData.extInfo.fromUserPhone"
              clearable /></el-form-item
        ></el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              clearable
              type="textarea"
              placeholder="请详细说明"
              :rows="4"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 选领料单 -->
    <pickOrder ref="pickOrderRef" @success="pickOrderRow" />
    <!-- 销售订单 -->
    <eom ref="eomRef" @success="eomSuccess" />
  </div>
</template>
<script>
  import warehouseDefinition from '@/api/warehouseManagement/warehouseDefinition';
  import selectTree from '@/components/selectTree';
  import pickOrder from './pickOrder.vue';
  import eom from './eom.vue';
  import { outputSceneState } from '@/utils/dict/index';
  export default {
    components: {
      pickOrder,
      eom,
      selectTree
    },
    props: {
      myFormData: {
        type: Object,
        default: {
          extInfo: {
            assetType: '', //物品类型id
            assetTypeName: '', //物品类型名称
            deptCode: '', //部门code
            deptName: '', //部门名称
            verifyDeptCode: '', //审核部门编码
            verifyDeptName: '', //审核部门名称
            deliveryName: '', //送货人名称
            fromUserPhone: '', //送货人电话
            sourceBizNo: '', //销售订单
            urgent: '', //紧急状态
            supplierId: '', //供应商ID
            supplierName: '', //供应商名称
            createUserName: '', //创建人名字
            contentImage: [] //图片数组
          },
          fromUser: '', //送货人
          bizType: '', //物品类型
          verifyId: '', //审核人Id
          verifyName: '', //审核人名称
          createUserId: '', // 创建人id
          remark: '' // 备注
        }
      },
      rules: {
        type: Object,
        default: {
          bizType: {
            required: true,
            message: '请选择出库场景',
            trigger: 'change'
          },
          fromUser: {
            required: true,
            message: '请选择领料人',
            trigger: 'change'
          }
        }
      },
      // 物品列表
      warehousingMaterialList: {
        type: Array,
        default: []
      }
    },
    watch: {
      myFormData: {
        handler(newValue) {
          this.formData = newValue;
        },
        immediate: false, // 立即先去执行里面的handler方法
        deep: true // 开启深度监听，默认是false
      },
      formData: {
        handler(newValue) {
          this.$emit('onFormChange', newValue);
        },
        immediate: false,
        deep: true
      }
    },
    data() {
      return {
        formData: this.myFormData,
        outputSceneState, // 出库场景列表
        options: [], // 备品备件来源单号列表
        treeList: [] // 领料人部门列表
      };
    },
    async created() {
      // 获取物品类型下拉选择树
      this.getAssetTypeList();
      // 获取领料人部门下拉列表
      this.getTreeList();
    },
    methods: {
      // 部门点击事件
      async auditorDeptClick(data) {
        console.log(data);
        this.formData.extInfo.verifyDeptCode = data?.id;
        this.formData.extInfo.verifyDeptName = data?.name;
        this.formData.verifyId = '';
        this.formData.verifyName = '';
        this.$refs.formName.validateField('verifyDeptName');
        if (data) {
          this.getStaffList(data);
        }
      },
      // 获取领料人部门下拉列表
      async getTreeList() {
        const res = await warehouseDefinition.tree();
        this.treeList = this.$util.toTreeData({
          data: res,
          idField: 'id',
          parentIdField: 'parentId'
        });
      },
      // 获取领料人下拉列表
      async getStaffList(data) {
        let res = await warehouseDefinition.getUserPage({
          groupId: data.id,
          size: 9999,
          page: 1
        });
        this.llrLsit = res.list;
      },
      // 物品类型Change事件
      assetTypeChange(val) {
        this.formData.extInfo.assetType = val?.id;
        this.$forceUpdate();
        // this.title = val?.name;
        this.formData.extInfo.assetTypeName = val?.name;
        this.selectEquiType = val?.id;
      },
      // 获取物品类型下拉选择树
      async getAssetTypeList() {
        const { data } = await getTreeByGroup({ type: 2 });
        this.codeList = data;
      },
      // 选择出库场景
      handleBizSceneChange() {
        if (this.formData.extInfo.assetType == 7) {
          this.formData.extInfo.sourceBizNo = '';
        }
        this.formData.sourceBizNo = '';
      },
      // 备品备件来源单号(无接口)
      async remoteMethod(code) {
        const res = await getDocumentSource({ code });
        if (res?.success) {
          this.options = res.data;
        }
      },
      handlePickorder() {
        this.$refs.pickOrderRef.open();
      },
      handleEom() {
        this.$refs.eomRef.open();
      },
      onClear() {
        this.formData.sourceBizNo = '';
        this.$emit('onClearMaterialList');
        this.$refs.trees.valueTitle = '';
        this.formData.clientName = '';
        this.formData.clientUser = '';
        this.formData.clientPhone = '';
        this.title = '';
        this.$forceUpdate();
      },
      async pickOrderRow(row) {
        this.formData.sid = row.id;
        row.tableData = [];
        this.formData.sourceBizNo = row.code;
        for (const key in row.orderInfoList) {
          if (row.orderInfoList[key].bomDetailDTOS.length != 0) {
            for (const i in row.orderInfoList[key].bomDetailDTOS) {
              row.tableData.push({
                ...row.orderInfoList[key].bomDetailDTOS[i],
                code: row.orderInfoList[key].bomDetailDTOS[i].categoryCode,
                name: row.orderInfoList[key].bomDetailDTOS[i].categoryName,
                modelType: row.orderInfoList[key].bomDetailDTOS[i].model,
                id: row.orderInfoList[key].bomDetailDTOS[i].categoryId
              });
            }
          }
          if (row.orderInfoList[key].instanceList.length != 0) {
            for (const j in row.orderInfoList[key].instanceList) {
              row.tableData.push({
                ...row.orderInfoList[key].instanceList[j],
                code: row.orderInfoList[key].instanceList[j].categoryCode,
                name: row.orderInfoList[key].instanceList[j].categoryName,
                modelType: row.orderInfoList[key].instanceList[j].model,
                id: row.orderInfoList[key].instanceList[j].instanceId
              });
            }
          }
        }
        const uniqueItems = [];
        const uniqueIds = new Set();
        row.tableData.forEach((item) => {
          if (!uniqueIds.has(item.code)) {
            uniqueIds.add(item.code);
            uniqueItems.push(item);
          }
        });
        row.tableData = uniqueItems;
        console.log(row);
        this.$parent.onSelectTableData(
          await this.$parent.serachMainCode(row.tableData),
          1
        );
        this.selectTop(row);
        this.$forceUpdate();
      },
      async eomSuccess(row) {
        console.log(row);
        this.formData.extInfo.assetType = 9;
        this.$refs.trees.valueTitle = '产品';
        this.title = '产品';
        this.formData.sourceBizNo = row.orderNo;
        this.formData.sid = row.id;
        this.formData.fromId = row.id;
        this.formData.clientName = row.contactName;
        this.formData.clientUser = row.linkName;
        this.formData.clientPhone = row.linkPhone;
        console.log('==sasa', row.tableData);
        this.$parent.onSelectTableData(
          await this.$parent.serachMainCode(row.tableData),
          1
        );
        this.$forceUpdate();
      },
      async handleDocumentSourceChange() {
        // this.formData.sourceBizNo = '';
        if (!this.formData.sourceBizNo) {
          if (this.formData.bizType == 4) {
            this.$emit('onClearMaterialList');
          }
          return;
        }

        if (
          !(this.formData.extInfo.assetType == 7 && this.formData.bizType == 4)
        ) {
          return;
        }

        const loading = this.$loading({ fullscreen: true });
        // 暂未用到(getSparePartsInfo无此接口) ----下面代码无效
        const res = await getSparePartsInfo({
          code: this.formData.sourceBizNo
        });
        if (res?.success && res.data.length) {
          const curMap = {
            assetId: 'classificationId',
            assetCode: 'informationCode', //编码
            assetName: 'informationName', //名称
            materialId: 'classificationId',
            materialName: 'informationName',
            batchNo: '', //批次号
            unit: 'measuringUnit', //单位
            minPackUnit: 'packingUnit' //最小包装单位
          };

          res.data.forEach((item) => {
            let obj = {};
            for (const key in curMap) {
              obj[key] = curMap[key] ? item[curMap[key]] : '';
            }
            obj.curId =
              obj.assetCode +
              (obj.measurementUnit || '') +
              (obj.minPackUnit || '') +
              (obj.unit || '');
            console.log(obj.curId);
            const index = this.warehousingMaterialList.findIndex(
              (i) => i.curId === obj.curId
            );
            if (index === -1) {
              Object.assign(obj, item);
              obj.sparePartsNum = item.num;

              this.warehousingMaterialList.push(obj);
            } else {
              this.warehousingMaterialList[index].sparePartsNum = item.num;
            }
          });
        }
        loading.close();
      }
    }
  };
</script>
