<template>
  <el-dialog
    :visible.sync="visible"
    :title="`${type}仓库`"
    :before-close="cancel"
    width="500px"
  >
    <el-form
      v-loading="loadingVis"
      :model="formData"
      :rules="rules"
      ref="formRef"
      label-width="100px"
    >
      <el-form-item label="仓库编码" prop="code">
        <el-input
          v-model="formData.code"
          :disabled="type != '新建'"
          placeholder="请输入"
          size="small"
        ></el-input>
      </el-form-item>
      <el-form-item label="仓库名称" size="small" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="限16个文字"
          maxlength="16"
        ></el-input>
      </el-form-item>
      <el-form-item label="物品类型" prop="warehouseType">
        <el-select
          filterable
          size="small"
          class="w100"
          v-model="formData.warehouseType"
          placeholder="物品类型"
          :clearable="true"
        >
          <el-option
            v-for="item in warehousetypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="仓库类型" prop="inventoryType">
        <!-- <DictSelection
          dictName="仓库类型"
          clearable
          v-model="formData.inventoryType"
        /> -->
        <el-select
          filterable
          size="small"
          class="w100"
          multiple
          v-model="formData.inventoryType"
          placeholder="请选择"
          @change="changeInventoryType"
        >
          <el-option
            v-for="item in inventoryTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属工厂" prop="factoryId">
        <el-select
          filterable
          size="small"
          class="w100"
          v-model="formData.factoryId"
          placeholder="请选择"
        >
          <el-option
            v-for="item in factoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            @click.native="
              () => (
                (formData.factoryName = item.name),
                (formData.factoryCodefactoryCode = item.code)
              )
            "
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="权属部门" prop="departmentId">
        <DeptSelect v-model="formData.departmentId" @input="nodeClick" />
      </el-form-item>
      <el-form-item label="仓管员" prop="ownerId">
        <el-select
          filterable
          class="w100"
          size="small"
          v-model="formData.ownerId"
          placeholder="请选择"
          @change="changeOwner"
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="联系方式" prop="contact">
        <el-input
          v-model="formData.contact"
          placeholder="请输入"
          size="small"
        ></el-input>
      </el-form-item>

      <el-form-item label="仓库位置" prop="location">
        <el-cascader
          size="small"
          class="w100"
          :props="{
            value: 'label',
            label: 'label',
            children: 'children'
          }"
          v-model="formData.location"
          :options="locationOptions"
          @change="changeLocation"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="详情地址" prop="address">
        <el-input
          v-model="formData.address"
          placeholder="请输入"
          size="small"
          @change="$forceUpdate()"
        ></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input
          type="textarea"
          v-model="formData.remarks"
          placeholder="请输入"
          size="small"
        ></el-input>
      </el-form-item>
      <el-form-item label="锁库状态" prop="lockStatus">
        <el-switch
          v-model="formData.lockStatus"
          active-text="锁库"
          inactive-text="开库"
          :active-value="1"
          :inactive-value="0"
        ></el-switch>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch
          v-model="formData.status"
          active-text="开"
          inactive-text="关"
          :active-value="1"
          :inactive-value="0"
        ></el-switch>
      </el-form-item>
    </el-form>
    <el-divider></el-divider>
    <div slot="footer">
      <el-button type="primary" plain @click="cancel">取消</el-button>
      <el-button type="primary" @click="handleSave" :loading="loading"
        >确定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import warehouseDefinition from '@/api/warehouseManagement/warehouseDefinition';

// import selectTree from '@/components/selectTree';
import DeptSelect from '@/components/CommomSelect/new-dept-select.vue';

import { getByCode } from '@/api/system/dictionary-data';
// import city from '@/assets/js/city';
import { cityData } from 'ele-admin/packages/utils/regions';
// import user from '@/api/main/user';

export default {
  components: { DeptSelect },
  data() {
    return {
      visible: false,
      loading: false,
      formData: {
        code: '',
        name: '',
        inventoryType: [],
        inventoryName: [],
        remarks: '',
        factoryId: '',
        status: 1,
        lockStatus: 0,
        ownerId: '',
        departmentId: '',
        contact: '',
        warehouseType: ''
      },
      warehousetypeList: [],
      rules: {
        code: [{ required: true, message: '请输入仓库编码', trigger: 'blur' }],
        name: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
        inventoryType: [
          { required: true, message: '请选择仓库类型', trigger: 'blur' }
        ],
        factoryId: [
          { required: true, message: '请选择工厂名称', trigger: 'blur' }
        ],
        departmentId: [
          { required: true, message: '请选择权属部门', trigger: 'change' }
        ],
        ownerId: [
          { required: true, message: '请选择权属人', trigger: 'change' }
        ]
        // status: [
        //   { required: true, message: '请选择仓库状态', trigger: 'blur' }
        // ]
      },
      type: '新建',
      userList: [],
      deptList: [], //部门集合
      inventoryTypeList: [],
      factoryList: [], //工厂集合
      locationOptions: cityData,
      loadingVis: false
    };
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          // this.init();
        }
      }
    },

    loadingVis: {
      handler(val) {
        console.log(val);
        if (!val && this.type == '新建') {
          this.formData = {
            code: '',
            name: '',
            inventoryType: [],
            inventoryName: [],
            remarks: '',
            factoryId: '',
            status: 1,
            lockStatus: 0,
            ownerId: '',
            departmentId: ''
          };
        }
      }
    }
  },
  created() {
    this.getwarehousetypeCode('warehouse_type');
  },
  methods: {
    async getwarehousetypeCode(code) {
      console.log(code);
      try {
        const res = await getByCode(code);
        if (res.code == 0) {
          let list = Object.values(res.data).map((el) => {
            let k = Object.keys(el)[0];
            let v = Object.values(el)[0];
            return { label: v, value: k };
          });
          this.warehousetypeList = list;
          console.log(this.warehousetypeList);
        }
      } catch (err) {
        this.$message.error(err.message);
      }
    },
    async open(type, row) {
      console.log(type);
      this.type = type;
      this.visible = true;
      this.init();
      console.log('locationOptions', this.locationOptions);
      if (type === '修改') {
        console.log(1);
        this.loadingVis = true;
        this.$nextTick(async () => {
          setTimeout(async () => {
            const { warehouseVO } = await warehouseDefinition.warehouseDetail(
              row.id
            );
            if (warehouseVO.departmentId) {
              let userData = await warehouseDefinition.getUserPage({
                groupId: warehouseVO.departmentId,
                size: 9999,
                pageNum: 1
              });
              this.userList = userData.list;
            }
            this.formData = {
              ...warehouseVO,
              location: [
                warehouseVO.province,
                warehouseVO.city,
                warehouseVO.area
              ],
              inventoryType: warehouseVO.inventoryType.split(','),
              inventoryName: warehouseVO.inventoryName.split(',')
            };
            this.loadingVis = false;
          }, 2000);
        });
      } else {
        this.formData = {
          code: '',
          name: '',
          inventoryType: [],
          inventoryName: [],
          remarks: '',
          factoryId: '',
          status: 1,
          lockStatus: 0,
          ownerId: '',
          departmentId: ''
        };
      }

      // if (type === '新建') {
      //   let num = 1
      //   const res = await warehouseList()
      //   if (res?.success && res.data?.length) {
      //     num = +res.data[0].code.substr(1) + 1
      //   }
      // this.formData.code = 'A' + pushZero(num)
      // }
    },
    async init() {
      // org.tree().then((tree) => {
      //   if (tree?.success) {
      //     this.deptList = tree.data;
      //   }
      // });
      // const tree = await warehouseDefinition.tree();

      // this.deptList = this.$util.toTreeData({
      //   data: tree,
      //   idField: 'id',
      //   parentIdField: 'parentId'
      // });

      //获取工厂车间列表
      const res = await warehouseDefinition.getFactoryarea({
        pageNum: 1,
        size: 9999,
        type: 1
      });

      // let data = org.factorys({ status: true });
      this.factoryList = res.list;

      const res2 = await warehouseDefinition.getTreeByGroup({ type: 2 });
      this.inventoryTypeList = res2;
    },
    changeInventoryType(val) {
      console.log(val, '1');
      // 根据选中的仓库类型ID数组，获取对应的名称数组
      const inventoryNames = val
        .map((typeId) => {
          const item = this.inventoryTypeList.find(
            (item) => item.id === typeId
          );
          return item ? item.name : '';
        })
        .filter((name) => name !== '');

      this.formData.inventoryName = inventoryNames;
      console.log('仓库类型名称数组:', this.formData.inventoryName);
    },

    handleSave() {
      this.$refs.formRef.validate(async (value) => {
        if (value) {
          let params = Object.assign(this.formData);
          params.inventoryType = params.inventoryType.join(',');
          params.inventoryName = params.inventoryName.join(',');

          // if (params.location?.length) {
          //   const [province, city, area] = params.location;

          //   Object.assign(params, {
          //     province,
          //     city,
          //     area
          //   });
          // }
          // delete params.location;
          // console.log(params);

          this.loading = true;
          const res = await warehouseDefinition
            .saveOrUpdateWarehouse(params)
            .finally(() => (this.loading = false));
          if (res.data?.code == '0') {
            this.$message.success('保存成功！');
            this.$emit('success');
            this.cancel();
          }
        }
      });
    },
    cancel() {
      this.$refs.formRef.resetFields();
      // this.$refs.tree.clearHandle();
      this.visible = false;
    },
    async nodeClick(id, data) {
      // this.formData.departmentCode = data?.code;
      this.formData.departmentId = id;
      if (data) {
        this.formData.departmentName = data.name;
      }
      this.formData.ownerName = '';
      this.formData.ownerId = '';
      if (id) {
        let userData = await warehouseDefinition.getUserPage({
          groupId: id,
          size: 9999,
          pageNum: 1
        });
        this.userList = userData.list;
      }
    },
    changeOwner(val) {
      this.formData.ownerId = val;
      let user = this.userList.find((item) => {
        return item.id == val;
      });
      console.log(user);

      this.formData.ownerName = user.name;

      this.formData.contact = user.phone;

      // this.$nextTick(() => {
      //   this.$forceUpdate();
      // });
      // this.$set(this.formData, 'ownerId', val);
      // this.$set(
      //   this.formData,
      //   'ownerName',
      //   this.userList.find((item) => {
      //     return item.id == val;
      //   }).name
      // );
      // console.log(this.formData);
      // this.$forceUpdate();
    },
    changeLocation(val) {
      console.log(val, '1~~~');
      this.$set(this.formData, 'province', val[0]); //省
      this.$set(this.formData, 'city', val[1]); //市
      this.$set(this.formData, 'area', val[2]); //区
      // delete this.formData.location;
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-form {
  .el-form-item {
    margin-bottom: 20px;
  }
}

.el-divider--horizontal {
  margin: 0 !important;
}
</style>
