<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="inventoryType">
        <el-select
          filterable
          placeholder="请选择"
          v-model="formData.inventoryType"
          clearable
          class="w100"
        >
          <el-option
            v-for="(item, idx) in warehouseDefinition_inventoryList"
            :key="item.code"
            :value="item.code"
            :label="item.label"
          ></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="location">
        <el-cascader
          size="small"
          class="w100"
          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 city from '@/assets/js/city';
  // import user from '@/api/main/user';

  export default {
    components: { DeptSelect },
    data() {
      return {
        warehouseDefinition_inventoryList: [
          { code: 1, label: '物料仓' },
          { code: 2, label: '产品仓' },
          { code: 3, label: '设备仓' },
          { code: 4, label: '模具仓' },
          { code: 5, label: '舟皿仓' },
          { code: 6, label: '备品备件仓' }
        ],
        visible: false,
        loading: false,
        formData: {
          code: '',
          name: '',
          inventoryType: '',
          remarks: '',
          factoryId: '',
          status: 1,
          lockStatus: 0
        },
        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' }
          // ],
          // status: [
          //   { required: true, message: '请选择仓库状态', trigger: 'blur' }
          // ]
        },
        type: '新建',
        userList: [],
        deptList: [], //部门集合
        factoryList: [], //工厂集合
        locationOptions: city,
        loadingVis: false
      };
    },
    watch: {
      visible: {
        handler(val) {
          if (val) {
            // this.init();
          }
        }
      }
    },
    created() {},
    methods: {
      open(type, row) {
        this.type = type;
        this.visible = true;
        this.init();

        if (type === '修改') {
          this.loadingVis = true;
          this.$nextTick(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
              ]
            };
            this.loadingVis = false;
          });
        }

        // 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;
      },

      handleSave() {
        this.$refs.formRef.validate(async (value) => {
          if (value) {
            const params = Object.assign(this.formData);

            // 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.$forceUpdate();
        this.$set(this.formData, 'ownerId', val);
        this.$set(
          this.formData,
          'ownerName',
          this.userList.find((item) => {
            return item.id == val;
          }).name
        );
      },
      changeLocation(val) {
        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>
