<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
        >
          <Collapse v-model="infoVal" class="coll-edit coll-search">
            <Panel name="1">
              基本信息
              <div slot="content">
                <Form-item label="中文名称" prop="lmsCustomer.cname" class="width-32">
                  <Input v-model="formObj.lmsCustomer.cname" name="cname" placeholder="请输入中文名称" />
                </Form-item>
                <Form-item label="英文名称" prop="lmsCustomer.ename" class="width-32">
                  <Input v-model="formObj.lmsCustomer.ename" name="ename" placeholder="请输入英文名称" />
                </Form-item>
                <Form-item label="信用等级" prop="lmsCustomer.credit" class="width-32">
                  <autoComplete
                    name="credit"
                    :value="formObj.lmsCustomer.credit"
                    placeholder="请输入或选择信用等级"
                    :down-data="creditList"
                    @on-result-change="_creditChange"
                  />
                </Form-item>
                <Form-item label="来源" prop="lmsCustomerDetail.origin" class="width-32">
                  <autoComplete
                    name="origin"
                    :value="formObj.lmsCustomerDetail.origin"
                    placeholder="请输入或选择来源"
                    :down-data="originList"
                    @on-result-change="_originChange"
                  />
                </Form-item>
                <Form-item label="网站" prop="lmsCustomerDetail.website" class="width-32">
                  <Input v-model="formObj.lmsCustomerDetail.website" name="website" placeholder="请输入网站" />
                </Form-item>
                <Form-item label="备注" prop="lmsCustomerDetail.remark" class="width-32">
                  <Input v-model="formObj.lmsCustomerDetail.remark" name="remark" placeholder="请输入备注" />
                </Form-item>
              </div>
            </Panel>
            <Panel name="2">
              财务信息
              <div slot="content">
                <Form-item label="税号" class="width-48" prop="lmsCustomer.taxation">
                  <Input v-model="formObj.lmsCustomer.taxation" placeholder="请输入税号" name="taxation" />
                </Form-item>
                <Form-item label="开户银行" prop="lmsCustomer.bank" class="width-48">
                  <autoComplete
                    name="bank"
                    :value="formObj.lmsCustomer.bank"
                    placeholder="请输入或选择开户银行"
                    :down-data="bankList"
                    @on-result-change="_bankChange"
                  />
                </Form-item>
                <Form-item label="账户" class="width-48" prop="lmsCustomer.bankAccount">
                  <Input v-model="formObj.lmsCustomer.bankAccount" placeholder="请输入账户" name="bankAccount" />
                </Form-item>
                <Form-item label="注册地址" class="width-48" prop="lmsCustomer.companyAddress">
                  <Input v-model="formObj.lmsCustomer.companyAddress" placeholder="请输入注册地址" name="companyAddress" />
                </Form-item>
                <Form-item label="公司电话" class="width-48" prop="lmsCustomer.billTell">
                  <Input v-model="formObj.lmsCustomer.billTell" placeholder="请输入公司电话" name="billTell" />
                </Form-item>
              </div>
            </Panel>
            <Panel name="3">
              联系方式
              <div slot="content">
                <Form-item label="主联系人" prop="lmsCustomer.contact" class="width-32">
                  <Input v-model="formObj.lmsCustomer.contact" name="contact" placeholder="请输入主联系人" />
                </Form-item>
                <Form-item label="联系手机" prop="lmsCustomer.mobile" class="width-32">
                  <Input v-model="formObj.lmsCustomer.mobile" name="mobile" placeholder="请输入联系手机" />
                </Form-item>
                <Form-item label="固定电话" prop="lmsCustomerDetail.phone" class="width-32">
                  <Input v-model="formObj.lmsCustomerDetail.phone" name="phone" placeholder="请输入固定电话" />
                </Form-item>
                <Form-item label="邮箱" prop="lmsCustomerDetail.email" class="width-32">
                  <Input v-model="formObj.lmsCustomerDetail.email" name="email" placeholder="请输入邮箱" />
                </Form-item>
                <Form-item label="传真" prop="lmsCustomerDetail.fax" class="width-32">
                  <Input v-model="formObj.lmsCustomerDetail.fax" name="fax" placeholder="请输入传真" />
                </Form-item>
                <Form-item label="邮寄地址" prop="lmsCustomerDetail.postAddress" class="width-32">
                  <Tooltip content="长度为0-100" placement="bottom-start">
                    <Input
                      v-model="formObj.lmsCustomerDetail.postAddress"
                      name="postAddress"
                      placeholder="请输入邮寄地址"
                      style="width: 230px"
                      :maxlength="100"
                    />
                  </Tooltip>
                </Form-item>
                <Form-item label="邮寄方式" prop="lmsCustomerDetail.postWay" class="width-32">
                  <Select v-model="formObj.lmsCustomerDetail.postWay" name="postWay" filterable>
                    <Option v-for="item in postWayList" :key="item.value" :value="item.value">
                      {{ item.name }}
                    </Option>
                  </Select>
                </Form-item>
                <Form-item label="邮编" prop="lmsCustomerDetail.postcode" class="width-32">
                  <Input v-model="formObj.lmsCustomerDetail.postcode" name="postcode" placeholder="请输入邮编" />
                </Form-item>
              </div>
            </Panel>
            <Panel name="4">
              公司地址
              <div slot="content">
                <Form-item label="所属省" prop="lmsCustomerDetail.province" class="width-48">
                  <autoComplete
                    name="province"
                    :value="formObj.lmsCustomerDetail.province"
                    show-key="label"
                    placeholder="请选择所属省"
                    :down-data="provinceTypeData"
                    @on-result-change="_provinceTypeChange"
                  />
                </Form-item>
                <Form-item label="所属市" prop="lmsCustomerDetail.city" class="width-48">
                  <autoComplete
                    name="city"
                    :value="formObj.lmsCustomerDetail.city"
                    show-key="label"
                    placeholder="请选择所属市"
                    :down-data="cityTypeData"
                    @on-result-change="_cityTypeChange"
                  />
                </Form-item>
                <Form-item label="所属县" prop="lmsCustomerDetail.area" class="width-48">
                  <autoComplete
                    name="area"
                    :value="formObj.lmsCustomerDetail.area"
                    show-key="label"
                    placeholder="请选择所属县"
                    :down-data="countyTypeData"
                    @on-result-change="_countyTypeChange"
                  />
                </Form-item>

                <Form-item label="街道" prop="lmsCustomerDetail.street" class="width-48">
                  <Tooltip content="长度为0-50" placement="bottom-start">
                    <Input
                      v-model="formObj.lmsCustomerDetail.street"
                      name="street"
                      placeholder="请输入联系街道"
                      style="width:370px "
                      :maxlength="50"
                    />
                  </Tooltip>
                </Form-item>
                <Form-item label="经度" prop="lmsCustomerDetail.longitude" class="width-48">
                  <Input
                    v-model="formObj.lmsCustomerDetail.longitude"
                    name="longitude"
                    placeholder="请输入经度"
                    icon="android-pin"
                    @on-click="_selMap"
                  />
                </Form-item>
                <Form-item label="纬度" prop="lmsCustomerDetail.latitude" class="width-48">
                  <Input
                    v-model="formObj.lmsCustomerDetail.latitude"
                    name="latitude"
                    placeholder="请输入纬度"
                    icon="android-pin"
                    @on-click="_selMap"
                  />
                </Form-item>
                <Form-item label="主营业务" prop="lmsCustomerDetail.business" class="width-90">
                  <Input
                    v-model="formObj.lmsCustomerDetail.business"
                    name="business"
                    placeholder="请输入主营业务"
                    style="width:837px"
                    type="textarea"
                    autosize
                  />
                </Form-item>
              </div>
            </Panel>
          </Collapse>
        </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 { customer, 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: {
        lmsCustomer: {
          cname: '',
          contact: '',
          credit: '',
          ename: '',
          mobile: '',
          rank: '',
          status: 1,
          type: '',
          taxation: '', // 税务
          bank: '', // 开户银行
          bankAccount: '', // 账户
          companyAddress: '',
          billTell: ''
        },
        lmsCustomerDetail: {
          address: '',
          area: '',
          city: '',
          customer: '',
          email: '',
          fax: '',
          origin: '',
          phone: '',
          postAddress: '',
          postWay: 0,
          postcode: '',
          province: '',
          remark: '',
          street: '',
          website: '',
          longitude: '',
          latitude: '',
          business: ''
        }
      },
      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 customer.add(data)
        this._resultChange(result, '添加成功!')
      } else {
        const result = await customer.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 = '编辑企业'
          this.isLogo = true
          this.action = global.baseURL + '/base/v1/company/logo_' + formObj.id
          if (formObj.logo) {
            // 有logo
            this.showLogo = true
            this.imgUri =
              global.baseURL + '/base/v1/company/logo?key=' + formObj.logo
          } else {
            // 无logo
            this.showLogo = false
          }
        }
      })
    },
    _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>
