<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="extInfo.assetType">
            <select-tree
              ref="tree"
              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">
          <el-form-item label="入库类型" prop="bizType">
            <el-select
              @change="onClear"
              filterable
              style="width: 100%"
              placeholder="请选择"
              v-model="formData.bizType"
              clearable
            >
              <el-option
                v-for="item in sceneState"
                :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
            v-if="formData.bizType == 2"
            label="采购收货单"
            prop="documentSource"
          >
            <el-input
              placeholder="请输入"
              v-model="formData.extInfo.documentSource"
              @click.native="handlePicker()"
            >
              <el-button
                slot="append"
                icon="el-icon-circle-close"
                @click.stop="onClear"
              ></el-button>
            </el-input>
          </el-form-item>
          <el-form-item
            v-if="formData.bizType == 1"
            label="生产工单"
            prop="documentSource"
          >
            <el-input
              placeholder="请输入"
              clearable
              v-model="formData.extInfo.documentSource"
          /></el-form-item>
          <el-form-item
            v-if="
              formData.bizType != 1 &&
              formData.bizType != 2 &&
              formData.bizType != 3
            "
            label="销售订单"
            prop="documentSource"
          >
            <el-input
              placeholder="请输入"
              clearable
              v-model="formData.extInfo.documentSource"
          /></el-form-item>
          <el-form-item
            v-if="formData.bizType == 3"
            label="出库单"
            prop="documentSource"
          >
            <el-input
              placeholder="请输入"
              clearable
              v-model="formData.extInfo.documentSource"
          /></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" v-if="formData.bizType == 2">
          <el-form-item label="供应商" prop="supplierName">
            <el-input
              placeholder="请输入"
              clearable
              v-model="formData.extInfo.supplierName"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="送货人" prop="fromUser">
            <el-input
              placeholder="请输入"
              v-model="formData.fromUser"
              clearable
            /> </el-form-item
        ></el-col>
        <el-col :span="8">
          <el-form-item label="送货人联系方式" prop="deliveryPhone">
            <el-input
              placeholder="请输入"
              v-model="formData.extInfo.deliveryPhone"
              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>
    <!-- 销售订单 -->
    <picker ref="pickerRef" @success="pickerSuccess" />
  </div>
</template>
<script>
  import warehouseDefinition from '@/api/warehouseManagement/warehouseDefinition';
  import { sceneState } from '@/utils/dict/index';
  import { getTreeByGroup, getProductList } from '@/api/classifyManage';
  import { getCode } from '@/api/codeManagement/index.js';
  import selectTree from '@/components/selectTree';
  import { contactlink, oneId } from '@/api/mes'; // 销售接口
  import picker from './picker.vue';
  export default {
    components: {
      picker,
      selectTree
    },
    props: {
      myFormData: {
        type: Object,
        default: {
          extInfo: {
            assetType: '', //物品类型id
            assetTypeName: '', //物品类型名称
            deptCode: '', //部门code
            deptName: '', //部门名称
            verifyDeptCode: '', //审核部门编码
            verifyDeptName: '', //审核部门名称
            deliveryName: '', //送货人名称
            deliveryPhone: '', //送货人电话
            documentSource: '', //销售订单
            urgent: '', //紧急状态
            supplierId: '', //供应商ID
            supplierName: '', //供应商名称
            createUserName: '', //创建人名字
            contentImage: [] //图片数组
          },
          fromUser: '', //送货人
          bizType: '', // 入库类型
          verifyId: '', //审核人Id
          verifyName: '', //审核人名称
          createUserId: '', // 创建人id
          clientName: '', // 客户名称
          clientCode: '', // 客户编号
          remark: '' // 备注
        }
      },
      rules: {
        type: Object,
        default: {
          'extInfo.assetType': {
            required: true,
            message: '请选择物品类型',
            trigger: 'change'
          },
          bizType: {
            required: true,
            message: '请选择入库场景',
            trigger: 'change'
          }
        }
      }
    },
    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,
        sceneState, // 入库类型下拉列表
        codeList: [] // 物品类型下拉选择列表
      };
    },
    async created() {
      // 获取物品类型下拉选择树
      this.getAssetTypeList();
      // let obj = localStorage.getItem('orgInfo') ? JSON.parse(localStorage.getItem('orgInfo')): {};
      // this.formData.createUserName = obj.name;
      // this.formData.extInfo.deptName = obj.dept?.name;
      // this.formData.deptCode = obj.dept?.code;
      const treeData = await warehouseDefinition.tree();
      const info = JSON.parse(localStorage.getItem('info'));
      let obj = treeData.find(
        (item) => item.id === info.deptId[info.deptId.length - 1]
      );
      if (!obj) return;
      this.formData.extInfo.deptCode = obj.id;
      this.formData.extInfo.deptName = obj.name;
      this.formData.extInfo.createUserName = info.name;
      this.formData.createUserId = info.id;
    },
    methods: {
      // 验证表单
      formValidate() {
        return new Promise((resolve, reject) => {
          this.$refs.formName.validate((valid) => {
            if (valid) {
              resolve();
            } else {
              reject();
            }
          });
        });
      },
      // 获取物品类型下拉选择树
      async getAssetTypeList() {
        const { data } = await getTreeByGroup({ type: 2 });
        this.codeList = data;
      },
      // 物品类型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;
      },
      // 清空操作
      onClear() {
        this.formData.extInfo.documentSource = '';
        this.pickerRow = {};
        this.formData.clientName = '';
        this.formData.clientCode = '';
        this.formData.extInfo.supplierName = '';
        this.formData.extInfo.supplierId = '';
        this.$forceUpdate();
      },
      // 销售相关逻辑(待修改)
      async pickerSuccess(row) {
        this.pickerRow = row;
        this.formData.extInfo.documentSource = row.orderNo;
        this.formData.clientName = row.partaName;
        this.formData.clientCode = row.partaId;
        this.formData.extInfo.supplierName = row.partbName;
        this.formData.extInfo.supplierId = row.partbId;
        const data = await oneId(row.id);
        // 产品信息列表
        if (this.$parent.warehousingMaterialList.length == 0) {
          console.log('data===', data);
          let list = data.data.productList.map((item) => {
            return {
              ...item,
              assetName: item.productName,
              assetCode: item.productCode,
              categoryId: item.productCategoryId
            };
          });
          // 添加明细
          this.$parent.onSelectTableData(await this.serachMainCode(list));
        }
      },
      // 销售相关逻辑(待修改)
      async serachMainCode(arr) {
        let newArr = [];
        // 使用 Promise.all 来等待所有异步操作完成
        await Promise.all(
          arr.map(async (item) => {
            const data = await getProductList({
              pageNum: 1,
              size: 10,
              categoryLevelId: item.categoryLevelPathIdParent,
              code: item.assetCode
            });
            newArr.push(data.list); // 将结果存储到 newArr 中
          })
        );
        let re = [];
        for (const item of newArr) {
          for (const it of item) {
            re.push(it);
          }
        }
        return re.map((item) => {
          return {
            ...item,
            minPackUnit: item.packingUnit,
            assetCode: item.code,
            assetName: item.name
          };
        });
      },
      // 展开采购单
      handlePicker() {
        this.$refs.pickerRef.open();
      }
    }
  };
</script>
