<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="8vh"
    width="1040px"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    @close="showModelThis = false"
  >
    <el-card style="margin-top: -20px">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            status-icon
            :size="'mini'"
            :rules="rulesThis"
            label-width="100px"
            class="demo-ruleForm"
          >
            <div style="padding: 0 0 12px 0">
              <el-divider content-position="center">仓库信息</el-divider>
            </div>

            <el-row>
              <el-col
                :span="12"
              ><el-form-item
                label-width="140px"
                label="仓库所在业务公司"
                prop="companyNo"
              >
                <search-work-company
                  :value="ruleForm.companyNo"
                  :placeholder="'业务公司'"
                  :disabled="isDetail || isUpdate"
                  :size="'mini'"
                  :is-detail="false"
                  @searchChange="companyNosearchChange"
                />
              </el-form-item>
              </el-col>
              <!-- <el-col :span="12"
                ><el-form-item
                  label="仓库所在公司"
                  prop="supplierNo"
                  label-width="120px"
                  style="width: 100%"
                >
                  <search-supplier
                    :value="ruleForm.supplierNo"
                    :names="supplier_name"
                    :is-detail="id !== 'add'"
                    :size="'mini'"
                    :disabled="isDetail"
                    :placeholder="'仓库公司名称'"
                    @searchChange="supplierChange"
                  />
                </el-form-item>
              </el-col> -->
              <el-col :span="12">
                <el-form-item label="仓库名称" prop="name">
                  <el-input
                    v-model="ruleForm.name"
                    placeholder="仓库名称"
                    filterable
                    :disabled="isDetail"
                    maxlength="50"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="仓库类型" prop="wsmtype">
                  <el-select
                    v-model="ruleForm.wsmtype"
                    style="width: 100%"
                    :disabled="isDetail || isUpdate"
                    placeholder="仓库类型"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="仓库负责人" prop="contactor_id" style="width: 100%">
                  <search-account
                    :value="ruleForm.contactor_id"
                    :placeholder="'仓库负责人'"
                    :is-detail="id !== 'add'"
                    :disabled="isDetail"
                    :size="'mini'"
                    :names="accountNames"
                    @searchChange="accountChange"
                  /> </el-form-item></el-col>
              <el-col :span="12">
                <el-form-item label="负责人电话" prop="mobile">
                  <el-input
                    v-model="ruleForm.mobile"
                    placeholder="联系人电话"
                    maxlength="11"
                    clearable
                    :disabled="isDetail"
                  /> </el-form-item></el-col>
              <el-col :span="12">
                <el-form-item
                  label="仓库所在省/市/区"
                  prop="addr_code"
                  label-width="140px"
                >
                  <select-area
                    :placeholder="'仓库所在省/市/区'"
                    :value="ruleForm.addr_code"
                    :is-detail="id !== 'add'"
                    :size="'mini'"
                    :disabled="isDetail"
                    @selectChange="selectAreaAddr_code"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="仓库所在详细地址" prop="addr" label-width="140px">
                  <el-input
                    v-model="ruleForm.addr"
                    placeholder="仓库所在详细地址"
                    maxlength="100"
                    clearable
                    :disabled="isDetail"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <div style="padding: 0 0 12px 0">
              <el-divider content-position="center">收发货信息</el-divider>
            </div>
            <el-row>
              <el-col :span="8">
                <el-form-item label="联系人" prop="wsm_name" label-width="68px">
                  <el-input
                    v-model="ruleForm.wsm_name"
                    placeholder="联系人"
                    maxlength="20"
                    :disabled="isDetail"
                    clearable
                  /> </el-form-item></el-col>
              <el-col :span="8">
                <el-form-item label="职位" prop="position" label-width="55px">
                  <el-input
                    v-model="ruleForm.position"
                    placeholder="职位"
                    maxlength="20"
                    :disabled="isDetail"
                    clearable
                  /> </el-form-item></el-col>
              <el-col :span="8">
                <el-form-item label="电话" prop="wsm_mobile" label-width="55px">
                  <el-input
                    v-model="ruleForm.wsm_mobile"
                    placeholder="电话"
                    maxlength="11"
                    :disabled="isDetail"
                    clearable
                  /> </el-form-item></el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item
                  label="收发货省/市/区"
                  prop="addrs_code"
                  label-width="121px"
                >
                  <select-area
                    :is-detail="id !== 'add'"
                    :disabled="isDetail"
                    :size="'mini'"
                    :value="ruleForm.addrs_code"
                    :placeholder="'收发货省/市/区'"
                    @selectChange="selectAreaAddrs_code"
                  /> </el-form-item></el-col>
              <el-col :span="12">
                <el-form-item label="收发货详细地址" prop="wsm_addr" label-width="126px">
                  <el-input
                    v-model="ruleForm.wsm_addr"
                    placeholder="收发货详细地址"
                    maxlength="100"
                    :disabled="isDetail"
                    clearable
                  /> </el-form-item></el-col>
            </el-row>
          </el-form>
        </el-col>
        <el-col :span="24" style="text-align: right">
          <el-button
            v-if="!isDetail"
            type="primary"
            :size="'mini'"
            @click="submitForm"
          >保 存
          </el-button>
          <el-button :size="'mini'" @click="showModelThis = false">{{
            isDetail ? "关 闭" : "取 消"
          }}</el-button>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import asyncRequest from '@/apis/service/serviceParam/storeSet'
import resToken from '@/mixins/resToken'
import { isMobile, isSpecialSymbol, hasSpace, isAddr } from '@/utils/validate'
import { mapGetters } from 'vuex'
export default {
  name: 'StoreSet',
  mixins: [resToken],
  props: ['showModel', 'id', 'isDetail'],
  computed: {
    isUpdate() {
      return this.id !== 'add' && !this.isDetail
    },
    ...mapGetters(['business_companyNo'])
  },
  data() {
    const validatemobile = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('联系方式不能为空！'))
      } else {
        if (!isMobile(value)) {
          callback(new Error('联系方式格式不正确！'))
        } else {
          callback()
        }
      }
    }
    const validatewsmmobile = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('联系方式不能为空！'))
      } else {
        if (!isMobile(value)) {
          callback(new Error('联系方式格式不正确！'))
        } else {
          callback()
        }
      }
    }
    const validateAddr = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('详细地址不能为空！'))
      } else {
        if (hasSpace(value)) {
          callback(new Error('不能出现/回车/换行符！'))
        } else if (isSpecialSymbol(value)) {
          callback(new Error('不能使用英文特殊字符！'))
        } else if (isAddr(value)) {
          callback()
        } else {
          callback(new Error('详细地址填写不规范！'))
        }
      }
    }
    return {
      supplier_name: '',
      accountNames: '',
      loading: false,
      title: '添加仓库',
      showModelThis: this.showModel,
      options: [
        // {
        //   value: "1",
        //   label: "系统仓",
        // },
        //   {
        //   value: "2",
        //   label: "虚拟仓",
        // },
        //     {
        //   value: "3",
        //   label: "自建仓",
        // },
        {
          value: '5',
          label: '销售仓'
        },
        {
          value: '4',
          label: '次品仓'
        }
      ],
      ruleForm: {
        companyNo: '',
        name: '', // 仓库名称
        // supplierNo: [], //供应商编码
        wsmtype: '', // 仓库类型 目前随便填
        addr_code: [], // 仓库省市区
        addr: '', // 仓库详细地址
        contactor_id: [], // 仓库联系人
        mobile: '', // 仓库联系方式
        position: '', // 联系人职位  目前随便填

        wsm_name: '', // 收发货联系人
        wsm_mobile: '', // 收发货联系方式
        wsm_addr: '', // 收发货地址详细
        addrs_code: [] // 收发货省市区
      },
      rulesThis: this.rules,
      rules: {
        name: [{ required: true, message: '仓库名称不能为空', trigger: 'blur' }],
        position: [{ required: true, message: '联系人职位不能为空', trigger: 'blur' }],
        wsmtype: [{ required: true, message: '请选择仓库类型', trigger: 'change' }],
        companyNo: [
          {
            required: true,
            message: '业务公司不能为空',
            trigger: 'change'
          }
        ],
        // supplierNo: [
        //   {
        //     type: "array",
        //     required: true,
        //     message: "供应商公司",
        //     trigger: "change",
        //   },
        // ],
        addr_code: [
          {
            type: 'array',
            required: true,
            message: '仓库所在省/市/区',
            trigger: 'change'
          }
        ],
        addr: [{ required: true, validator: validateAddr, trigger: 'blur' }],

        contactor_id: [
          {
            required: true,
            type: 'array',
            message: '仓库负责人',
            trigger: 'change'
          }
        ],

        mobile: [
          {
            required: true,
            validator: validatemobile,
            trigger: 'blur'
          }
        ],
        wsm_name: [
          { required: true, message: '收发货联系人', trigger: 'blur' },
          {
            min: 1,
            max: 20,
            message: '长度在 1 到 20 个字符',
            trigger: 'blur'
          }
        ],
        wsm_mobile: [
          {
            required: true,
            validator: validatewsmmobile,
            trigger: 'blur'
          }
        ],
        addrs_code: [
          {
            type: 'array',
            required: true,
            message: '收发货所在省/市/区',
            trigger: 'change'
          }
        ],
        wsm_addr: [
          { required: true, message: '收发货详细地址', trigger: 'blur' },
          {
            min: 1,
            max: 100,
            message: '长度在 1 到 100 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    showModel: function(val) {
      this.showModelThis = val
      if (val) {
        this.initForm()
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit('cancel')
      }
    }
  },
  methods: {
    // 业务公司选择
    async companyNosearchChange(e) {
      const { id, code, label } = e
      this.ruleForm.companyNo = code || ''
      this.$refs.ruleForm.validateField('companyNo')
    },
    // 供应商公司选择
    supplierChange(e) {
      if (e && e.id) {
        this.ruleForm.supplierNo = [e.code] // 供应商编码
      } else {
        this.ruleForm.supplierNo = []
      }
      this.$refs.ruleForm.validateField('supplierNo')
    },
    // 仓库省市区
    selectAreaAddr_code(e) {
      this.ruleForm.addr_code = e
      this.$refs.ruleForm.validateField('addr_code')
    },
    // 收发货省市区
    selectAreaAddrs_code(e) {
      this.ruleForm.addrs_code = e
      this.$refs.ruleForm.validateField('addrs_code')
    },
    // 负责人选择
    accountChange(e) {
      if (e && e.id) {
        this.ruleForm.contactor_id = [e.id]
      } else {
        this.ruleForm.contactor_id = []
      }
      this.$refs.ruleForm.validateField('contactor_id')
    },
    async initForm() {
      this.supplier_name = ''
      this.loading = true
      if (this.id === 'add') {
        this.title = '新建仓库'
        this.rulesThis = this.rules
        await this.resetForm()
      } else {
        if (this.isDetail) {
          this.title = '仓库详情'
          this.rulesThis = {}
        } else {
          this.title = '修改仓库'
          this.rulesThis = this.rules
        }
        await this.resetForm()
        await this.initData()
      }
      this.loading = false
    },
    async initData() {
      const res = await asyncRequest.detail({ id: this.id })
      if (res && res.code === 0 && res.data) {
        const {
          addr,
          addr_code,
          addrs_code,
          contactor,
          contactor_name,
          mobile,
          name,
          // supplierNo,
          supplier_name,
          wsm_addr,
          wsm_code,
          wsm_mobile,
          wsm_name,
          companyNo,
          position,
          wsm_type
        } = res.data

        this.supplier_name = supplier_name
        this.accountNames = contactor_name
        this.ruleForm = {
          companyNo: companyNo || this.business_companyNo || '',
          name: name, // 仓库名称
          // supplierNo: [supplierNo], //供应商编码
          wsmtype: wsm_type || '', // 仓库类型 目前随便填
          addr_code: this.getCode(addr_code), // 仓库省市区
          addr: addr, // 仓库详细地址
          contactor_id: contactor ? [contactor] : [], // 仓库联系人
          mobile: mobile, // 仓库联系方式
          position: position || '', // 联系人职位  目前随便填
          wsm_type: '', // 目前随便填

          wsm_name: wsm_name, // 收发货联系人
          wsm_mobile: wsm_mobile, // 收发货联系方式
          wsm_addr: wsm_addr, // 收发货地址详细
          addrs_code: this.getCode(addrs_code) // 收发货省市区
        }
        console.log(this.ruleForm)

        // this.ruleForm = res.data;
        // this.ruleForm.role_id = this.ruleForm.role;
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout()
      } else {
        this.$message.warning(res.message)
      }
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields()
          this.$refs.ruleForm.clearValidate()
          this.supplier_name = ''
          this.accountNames = ''
          this.ruleForm = {
            companyNo: '',
            name: '', // 仓库名称
            // supplierNo: [], //供应商编码
            wsmtype: '', // 仓库类型 目前随便填
            addr_code: [], // 仓库省市区
            addr: '', // 仓库详细地址
            contactor_id: [], // 仓库联系人
            mobile: '', // 仓库联系方式
            position: '', // 联系人职位  目前随便填
            // wsm_type: "", //目前随便填

            wsm_name: '', // 收发货联系人
            wsm_mobile: '', // 收发货联系方式
            wsm_addr: '', // 收发货地址详细
            addrs_code: [] // 收发货省市区
          }
        }
      })
    },
    setCode(list) {
      const model = {
        provice_code: list[0],
        city_code: list[1],
        area_code: list[2]
      }
      return model
    },
    getCode(obj) {
      const arr = []
      arr.push(obj.provice_code)
      arr.push(obj.city_code)
      arr.push(obj.area_code)
      return arr
    },
    getId(list) {
      const arr = JSON.parse(JSON.stringify(list))
      return arr.join(',')
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          if (this.loading) {
            return
          }
          this.loading = true
          const {
            name,
            // supplierNo,
            addr_code,
            addr,
            contactor_id,
            mobile,
            wsm_name,
            wsm_mobile,
            wsm_addr,
            addrs_code,
            companyNo,
            position,
            wsmtype
          } = JSON.parse(JSON.stringify(this.ruleForm))
          const model = {
            id: this.id,
            companyNo,
            name,
            // supplierNo: this.getId(supplierNo),
            addr_code: this.setCode(addr_code),
            addr,
            contactor_id: this.getId(contactor_id),
            mobile,
            wsm_name,
            wsm_mobile,
            wsm_addr,
            addrs_code: this.setCode(addrs_code),
            position,
            // wsm_type: "", //目前随便填
            wsmtype
          }
          console.log(model)
          let res = {}
          if (this.id === 'add') {
            delete model['id']
            res = await asyncRequest.add(model)
          } else {
            res = await asyncRequest.update(model)
          }
          this.loading = false
          if (res && res.code === 0) {
            const title = this.id === 'add' ? '添加成功' : '修改成功'
            this.$notify.success({
              title,
              message: ''
            })
            this.showModelThis = false
            // 刷新
            this.$emit('refresh')
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout()
          } else {
            this.$message.warning(res.message)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.storeSet {
}
</style>
