<template>
  <CommonModal
    v-model="show"
    class="color-tag-modal"
    title="入库仓库"
    width="450"
    closable
    :on-confirm="onConfirm"
    @change="onVisibleChange"
  >
    <div class="modal-centent">
      <Form
        ref="form"
        :model="formData"
        :rules="rules"
        :label-width="135"
      >
        <FormItem
          label="入库实体仓"
          prop="physicalStorage"
        >
          <Select
            v-model="formData.physicalStorage.value"
            label-in-value
            filterable
            placeholder="请选择仓库"
            @on-change="onPhysicalStorageChange"
          >
            <Option
              v-for="item in physicalStorageList"
              :key="item.value"
              :value="item.value"
            >{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem
          label="默认入库逻辑仓"
          prop="defaultStorage"
        >
          <Select
            label-in-value
            filterable
            placeholder="请选择仓库"
            v-model="formData.defaultStorage.value"
            @on-change="onDefaultStorageChange"
          >
            <Option
              v-for="item in defaultStorageList"
              :key="item.value"
              :value="item.value"
            >{{ item.label }}</Option>
          </Select>
        </FormItem>

      </Form>
    </div>
  </CommonModal>
</template>

<script>
import CommonModal from '@yunque/component/modal/commonModal/index.vue';
import cloneDeep from 'lodash/cloneDeep'
const R3 = window.R3;
const { network, urlSearchParams } = R3;

export default {
  name: 'InStoreModal',

  components: {
    CommonModal,
  },

  props: {
    visible: {
      type: Boolean,
    },
    // 用户逻辑仓
    userPhysicalStorage: {
      type: Object,
    },
    // 用户实体仓
    userDefaultStorage: {
      type: Object,
    },
    // 默认用户逻辑仓
    allUserPhysicalStorage: {
      type: Object,
    },
    // 默认用户实体仓
    allUserDefaultStorage: {
      type: Object,
    },
    // 是否默认仓库
    openStoreType: {
      type: String
    }
  },

  model: {
    prop: 'visible',
    event: 'change',
  },

  watch: {
    visible(val) {
      this.show = val;
      if (val) {
        if(this.openStoreType == 'allUser'){
          this.formData.physicalStorage = cloneDeep(this.allUserPhysicalStorage)
          this.formData.defaultStorage = cloneDeep(this.allUserDefaultStorage)
        }else {
          this.formData.physicalStorage = cloneDeep(this.userPhysicalStorage)
          this.formData.defaultStorage = cloneDeep(this.userDefaultStorage)
        }

        this.getPhysicalStoreList().then(() => {
          if(this.openStoreType == 'allUser'){
            if (this.allUserPhysicalStorage.value) {
            this.getDefaultStoreList(this.allUserPhysicalStorage.value)
          }
          }else {
            if (this.userPhysicalStorage.value) {
              this.getDefaultStoreList(this.userPhysicalStorage.value)
            }
          }
        })
      }
    },

    userPhysicalStorage: {
      handler(val) {
        this.formData.physicalStorage = cloneDeep(val)
      },
      immediate: true
    },

    userDefaultStorage: {
      handler(val) {
        this.formData.defaultStorage = cloneDeep(val)
      },
      immediate: true
    }
  },

  data() {
    return {
      show: this.visible,
      formData: {
        physicalStorage: {
          value: '',
          label: ''
        },
        defaultStorage: {
          value: '',
          label: ''
        }
      },
      rules: {
        physicalStorage: [
          { required: true, message: '请选择入库实体仓', trigger: 'blur' }
        ],
        defaultStorage: [
          { required: true, message: '请选择默认入库逻辑仓', trigger: 'blur' }
        ],
      },
      physicalStorageList: [], // 实体仓列表
      defaultStorageList: [], // 默认逻辑仓列表
    };
  },

  mounted() {
  },

  methods: {
    // 获取实体仓库列表
    getPhysicalStoreList() {
      return network.post('/p/cs/store/getStoreList').then(res => {
        if (res.data.code === 0) {
          const data = res.data.data.map(item => {
            return {
              label: item.WAREHOUSENAME,
              value: item.ID
            }
          })
          // 只有一个仓库时
          if (data.length === 1) {
            this.formData.physicalStorage = data[0];
            this.getDefaultStoreList(this.formData.physicalStorage.value)
          }
          this.physicalStorageList = data
        }
      })
    },

    // 获取逻辑店仓列表
    getDefaultStoreList(id) {
      network.post('/p/cs/store/getStoreByhouseId', { ID: id }).then(res => {
        if (res.data.code === 0) {
          if (!res.data.data) {
            this.$Message.error({
              content: res.data.message,
              duration: 3
            })
            return
          }
          const data = res.data.data.map(item => {
            return {
              label: item.STORENAME,
              value: item.ID
            }
          })
          // 只有一个仓库时
          if (data.length === 1) {
            this.formData.defaultStorage = data[0];
          }
          this.defaultStorageList = data
        }
      })
    },

    // 修改实体仓
    onPhysicalStorageChange(val) {
      if(this.openStoreType == 'allUser'){
        this.formData.physicalStorage = val
        this.formData.defaultStorage = {
          value: '',
          label: ''
        }
      }else {
        this.formData.physicalStorage = val
        this.formData.defaultStorage = {
          value: '',
          label: ''
        }
      }
      this.defaultStorageList = []
      this.getDefaultStoreList(val.value)
    },

    // 修改逻辑仓
    onDefaultStorageChange(val) {
      if (val) {
        this.formData.defaultStorage = val
      } else {
        this.formData.defaultStorage = {
          value: '',
          label: ''
        }
      }
    },

    // 更新本地缓存的用户仓库
    updateLocalStore() {
      const localData = localStorage.getItem('firstDate') ? JSON.parse(localStorage.getItem('firstDate')) : [];
      const userId = JSON.parse(localStorage.getItem('userInfo')).id
      // 从本地缓存里查当前用户的仓库
      const userDataIndex = localData.findIndex(item => {
        return item.id === userId && item.storageList
      })
      // 如果有当前用户的数据，则更新缓存
      if(this.openStoreType == 'allUser'){
        if (userDataIndex > -1) {
          const newCache = {
            id: userId,
            storageList: {
              physicalStorage: this.formData.physicalStorage,
              defaultStorage: this.formData.defaultStorage
            },
            time: new Date().getTime()
          }
          localData[userDataIndex] = newCache
          localStorage.setItem('firstDate', JSON.stringify(localData));
        } else {
          const newCache = {
            id: userId,
            storageList: {
              physicalStorage: this.formData.physicalStorage,
              defaultStorage: this.formData.defaultStorage
            },
            time: new Date().getTime()
          }
          localStorage.setItem('firstDate', JSON.stringify([newCache]));
        }
      }
    },

    // 确定按钮回调
    onConfirm() {
      if (!this.formData.physicalStorage.value) {
        return this.$Message.warning('请选择入库实体仓');
      }
      if (!this.formData.defaultStorage.value) {
        return this.$Message.warning('请选择默认入库逻辑仓');
      }

      // 更新本地缓存的用户仓库
      this.updateLocalStore()

      this.$emit('change', false);
      this.$emit('on-confirm', this.formData);
    },

    // 处理modal关闭
    onVisibleChange(val) {
      if (!val) {
        this.$emit('change', false);
      }
    },
  },
};
</script>

<style lang="less" scoped>
</style>
<style lang="less">
.color-tag-modal {
  .ark-form-item-content {
    line-height: 26px;
  }
}
</style>
