<template>
  <div>
    <el-dialog
      v-dialogDrag
      :visible.sync="showModal"
      :close-on-click-modal="false"
      width="800px"
      :title="modalTitle"
    >
      <div>
        <Form
          id="edit-form"
          ref="formObj"
          :model="formObj"
          :rules="ruleValidate"
          :label-width="90"
          inline
        >
          <Form-item label="名称" prop="name">
            <Input v-model="formObj.name" name="name" placeholder="请输入名称" /></Input>
          </Form-item>
          <Form-item label="备注" prop="remark">
            <Input v-model="formObj.remark" name="remark" placeholder="请输入备注" /></Input>
          </Form-item>
        </Form>
      </div>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult" />
      </div>
    </el-dialog>
  </div>
</template>
<script>
/**
 * 添加编辑公司表
 */
import store from 'store2'
import { supplierType, resDict } from '../../../api'
import global from '../../../api/config'
export default {
  components: {},
  data() {
    const validateName = (rule, value, callback) => {
      // 验证名称
      const reg = /[\u4E00-\u9FA5_a-zA-Z]+$/
      if (value === '' || value === undefined) {
        callback(new Error('企业名称不能为空！'))
      } else if (!reg.test(value)) {
        callback(new Error('请输入中文或英文字符！'))
      } else {
        callback()
      }
    }
    const validateContact = (rule, value, callback) => {
      // 验证联系人
      const reg = /[\u4E00-\u9FA5_a-zA-Z]+$/
      if (value === '' || value === undefined) {
        callback()
      } else if (!reg.test(value)) {
        callback(new Error('请输入中文或英文字符！'))
      } else {
        callback()
      }
    }
    const validateBusno = (rule, value, callback) => {
      // 验证营业执照编号
      const reg = /[A-Za-z0-9]+$/
      if (value === '' || value === undefined) {
        callback()
      } else if (!reg.test(this.formObj.busno)) {
        callback(new Error('请输入英文和数字！'))
      } else {
        callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      // 验证手机号
      const reg = /^((\+?86)|(\(\+86\)))?1\d{10}$/
      if (
        this.formObj.contactWay === '' ||
        this.formObj.contactWay === undefined
      ) {
        callback()
      } else if (!reg.test(this.formObj.contactWay)) {
        callback(new Error('请输入正确格式的手机号！'))
      } else {
        callback()
      }
    }
    const validateDomain = (rule, value, callback) => {
      // 二级域名判定
      const reg = /[A-Za-z0-9_]+$/
      if (value === '') {
        callback()
      } else if (!reg.test(this.formObj.domain)) {
        //
        callback(new Error('只能输入字母、数字、下划线！'))
      } else {
        callback()
      }
    }
    return {
      isLogo: false, // 是否显示上传logo
      id: '',
      modalTitle: '添加客户信息',
      formObj: {
        name: '',
        remark: ''
      },
      typeList: [
        { value: 1, label: '第一方企业' },
        { value: 2, label: '第三方检测' },
        { value: 3, label: '其它' }
      ],
      statusList: [{ value: 0, label: '禁用' }, { value: 1, label: '正常' }],
      ruleValidate: {
        busno: [{ validator: validateBusno, trigger: 'blur' }],
        contactWay: [{ validator: validatePhone, trigger: 'blur' }],
        name: [{ required: true, validator: validateName, trigger: 'blur' }],
        domain: [{ validator: validateDomain, trigger: 'blur' }],
        contact: [{ validator: validateContact, trigger: 'blur' }],
        sort: [
          {
            required: true,
            message: '排序不能为空',
            trigger: 'blur',
            type: 'number'
          }
        ]
      },
      showModal: false,
      uploadList: [],
      action: '',
      dataObj: {
        file: '',
        companyId: ''
      },
      imgUri: '',
      cityData: [],
      footerList: [
        { id: '', name: '取消', type: '' },
        { id: '', name: '保存', type: 'primary' }
      ],
      showLogo: false,
      businessList: [],
      accept: '.jpg,.jpeg,.png,.JPEG,.PNG,.JPG'
    }
  },
  mounted() {
    this._dicSearch()
  },
  methods: {
    // 查询字典
    _dicSearch: async function() {
      const result = await resDict.getItem('业务类型')
      this.businessList = result
    },
    _footerResult(name) {
      switch (name) {
        case '取消':
          this._cancel()
          break
        case '保存':
          this._ok()
          break
      }
    },
    _cascaderResult(name, data) {
      if (data.selectedData.length > 0) {
        const provinceCode = data.selectedData[0]
          ? data.selectedData[0].code
          : ''
        const cityCode = data.selectedData[1] ? data.selectedData[1].code : ''
        const areaCode = data.selectedData[2] ? data.selectedData[2].code : ''

        this.formObj.provinceCode = provinceCode
        this.formObj.cityCode = cityCode
        this.formObj.areaCode = areaCode
        this.cityData = [provinceCode, cityCode, areaCode]
      } else {
        this.formObj.provinceCode = ''
        this.formObj.cityCode = ''
        this.formObj.areaCode = ''
        this.cityData = []
      }
    },
    _selectType(data) {
      this.formObj.type = data
    },
    _selectNotifyWechat(data) {
      this.formObj.notifyWechat = data
    },
    _selectStatus(data) {
      this.formObj.status = data
    },
    _resultChange(result, msg) {
      if (result) {
        this.showModal = false
        this.$message.success(msg)
        this.$emit('on-result-change')
      }
      this.$refs.footerModal._hideLoading()
    },
    _ok() {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize('edit-form')
          this._save(data)
        } else {
          this.$refs.footerModal._hideLoading()
          this.$message.error('表单验证失败!')
        }
      })
    },
    _save: async function(data) {
      if (this.$string(this.id).isEmpty()) {
        const result = await supplierType.add(data)
        this._resultChange(result, '添加成功!')
      } else {
        const result = await supplierType.edit({
          id: this.formObj.id,
          obj: data
        })
        this._resultChange(result, '编辑成功!')
      }
    },
    _cancel() {
      this.$refs.footerModal._hideLoading()
      this.showModal = false
    },
    _open(formObj) {
      this.showModal = true
      this.$nextTick(() => {
        this.$refs.footerModal._hideLoading()
        this.$refs.formObj.resetFields()
        this.cityData = []
        if (this.$string(formObj).isEmpty()) {
          this.id = ''
          this.modalTitle = '添加供应商类别'
          this.isLogo = false
        } else {
          this.id = formObj.id
          this.formObj = formObj
          if (formObj.provinceCode) {
            this.cityData = [
              formObj.provinceCode,
              formObj.cityCode,
              formObj.areaCode
            ]
          }
          this.modalTitle = '编辑供应商类别'
        }
      })
    },
    _beupload(file) {
      this.dataObj.file = file.name
      this.dataObj.companyId = this.id
    },
    _handelprogress() {
      this.$Spin.show({
        render: h => {
          return h('div', [
            h('Icon', {
              class: 'upload-spin-icon-load',
              props: {
                type: 'load-c',
                size: 18
              }
            }),
            h('div', '图片上传中，请稍后...')
          ])
        }
      })
    },
    _handelsuccess(response, file, fileList) {
      // 上传成功
      this.$Spin.hide()
      if (response.success) {
        this.$message.success('上传成功！')
        this.imgUri =
          global.baseURL + '/base/v1/company/logo?key=' + response.data
        store.set('logo', response.data)
        this.showLogo = true
      } else {
        this.$message.error('上传失败！')
        this.showLogo = false
      }
    },
    _handleFormatError(file) {
      this.$Notice.warning({
        title: '图片格式不正确',
        desc: '图片 ' + file.name + ' 格式不正确，请上传格式为jpg,png的图片！'
      })
    },
    _handleMaxSize(file) {
      this.$Notice.warning({
        title: '图片过大',
        desc: '图片  ' + file.name + ' 过大, 图片大小要＜1M.'
      })
    }
  }
}
</script>
<style scoped>
.logo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}

.logo-upload-list img {
  width: 100%;
  height: 100%;
}
</style>
