<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" class="width-48">
            <el-tooltip content="只能输入中英文且长度为0-40" placement="bottom-start">
              <el-input
                v-model="formObj.name"
                name="name"
                placeholder="请输入企业名称"
                style="width: 100%"
                :maxlength="40"
              />
            </el-tooltip>
          </Form-item>
          <Form-item label="营业执照编号" prop="busno" class="width-48">
            <el-tooltip content="只能输入英文和数字" placement="bottom-start">
              <el-input v-model="formObj.busno" name="busno" placeh older="请输入营业执照编号" style="width: 100%" />
            </el-tooltip>
          </Form-item>
          <Form-item label="联系人" prop="contact" class="width-48">
            <el-tooltip content="只能输入中英文且长度为0-10" placement="bottom-start">
              <el-input
                v-model="formObj.contact"
                name="contact"
                placeholder="请输入联系人"
                style="width: 100%"
                :maxlength="10"
                show-word-limit
              />
            </el-tooltip>
          </Form-item>
          <Form-item label="手机号" prop="contactWay" class="width-48">
            <el-input v-model="formObj.contactWay" name="contactWay" placeholder="请输入手机号" />
          </Form-item>
          <Form-item label="省、市、区" prop="area" class="width-48">
            <cityCodeCascader :value="cityData" @on-result-change="_cascaderResult" />
          </Form-item>
          <Form-item label="街道" prop="contactAddress" class="width-48">
            <el-input
              v-model="formObj.contactAddress"
              name="contactAddress"
              placeholder="请输入街道"
              style="width: 100%"
              :maxlength="100"
              show-word-limit
            />
          </Form-item>
          <Form-item label="经度" prop="longitude" class="width-48">
            <el-input v-model="formObj.longitude" name="longitude" placeholder="请输入经度" />
          </Form-item>
          <Form-item label="纬度" prop="latitude" class="width-48">
            <el-input v-model="formObj.latitude" name="latitude" placeholder="请输入纬度" />
          </Form-item>
          <Form-item label="电话" prop="phone" class="width-48">
            <el-input v-model="formObj.phone" name="phone" placeholder="请输入电话" />
          </Form-item>
          <Form-item label="传真" prop="fax" class="width-48">
            <el-input v-model="formObj.fax" name="fax" placeholder="请输入传真" />
          </Form-item>
          <Form-item label="邮编" prop="zipcode" class="width-48">
            <el-input v-model="formObj.zipcode" name="zipcode" placeholder="请输入邮编" />
          </Form-item>
          <Form-item label="网址" prop="website" class="width-48">
            <el-input v-model="formObj.website" name="website" placeholder="请输入网址" />
          </Form-item>
          <Form-item label="二级域名" prop="domain" class="width-48">
            <el-tooltip content="只能输入字母数字下划线" placement="bottom-start">
              <el-input
                v-model="formObj.domain"
                name="domain"
                placeholder="请输入二级域名"
                style="width: 100%"
                :maxlength="30"
                show-word-limit
              />
            </el-tooltip>
          </Form-item>
          <Form-item label="通知微信" prop="notifyWechat" class="width-48">
            <el-radio-group v-model="formObj.notifyWechat" @change="_selectNotifyWechat">
              <el-radio v-for="item in notifyWechatList" :key="item.value" :label="item.value">
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </Form-item>
          <Form-item label="类型" prop="type" style="width:100%">
            <el-radio-group v-model="formObj.type" @change="_selectType">
              <el-radio v-for="item in typeList" :key="item.value" :label="item.value">
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </Form-item>
          <Form-item label="状态" prop="status" class="width-48">
            <el-radio-group v-model="formObj.status" @change="_selectStatus">
              <el-radio v-for="item in statusList" :key="item.value" :label="item.value">
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </Form-item>
          <Form-item label="业务类型" prop="business" class="width-48">
            <el-select v-model="formObj.business" style="width:100%" clearable>
              <el-option v-for="item in businessList" :key="item.name" :value="item.name">
                {{ item.name }}
              </el-option>
            </el-select>
          </Form-item>
          <Form-item label="排序" prop="sort" class="width-48">
            <el-input-number
              v-model.number="formObj.sort"
              name="sort"
              placeholder="请输入排序"
              :min="1"
              style="width: 98%"
              size="small"
              controls-position="right"
              step-strictly
            />
          </Form-item>
          <Form-item v-if="isLogo" label="公司logo" prop="logo" class="width-48">
            <div style="width:58px;float: left;margin-right: 10px">
              <Tooltip content="建议图片大小：175 x 60 px" placement="top-start">
                <el-upload
                  :action="action"
                  :with-credentials="true"
                  :show-file-list="false"
                  :accept="accept"
                  :data="dataObj"
                  :on-progress="_handelprogress"
                  :before-upload="_beupload"
                  :on-success="_handelsuccess"
                >
                  <div
                    style="width: 58px;height:58px;line-height: 58px;border: 1px dashed #2a8df3;text-align: center;cursor: pointer"
                  >
                    <i class="iconfont pt-upload gray-color" size="20" />
                  </div>
                </el-upload>
              </Tooltip>
            </div>
            <div v-show="showLogo" class="logo-upload-list">
              <img :src="imgUri" alt="logo">
            </div>
          </Form-item>
          <Form-item label="备注" prop="remark" class="width-48">
            <el-input
              v-model="formObj.remark"
              name="remark"
              placeholder="请输入备注"
              :maxlength="100"
              show-word-limit
            />
          </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 { sysCompany, resDict } from '../../../api'
import global from '../../../api/config'
import cityCodeCascader from '../../../components/base/cityCodeCascader'

export default {
  components: {
    cityCodeCascader
  },
  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: {
        busno: '',
        contact: '',
        contactAddress: '',
        contactWay: '',
        domain: '',
        name: '',
        remark: '',
        sort: 1,
        notifyWechat: 0,
        status: 1,
        type: 1,
        phone: '',
        website: '',
        zipcode: '',
        fax: '',
        provinceCode: '',
        cityCode: '',
        areaCode: '',
        longitude: '',
        latitude: '',
        business: ''
      },
      typeList: [
        { value: 1, label: '第一方企业' },
        { value: 2, label: '第三方检测' },
        { value: 3, label: '其它' }
      ],
      notifyWechatList: [{ value: 0, label: '否' }, { value: 1, 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.$extend(data, {
            type: this.formObj.type,
            notifyWechat: this.formObj.notifyWechat,
            status: this.formObj.status,
            business: this.formObj.business,
            provinceCode: this.formObj.provinceCode,
            cityCode: this.formObj.cityCode,
            areaCode: this.formObj.areaCode
          })
          this._save(data)
        } else {
          this.$refs.footerModal._hideLoading()
          this.$message.error('表单验证失败!')
        }
      })
    },
    _save: async function(data) {
      if (this.$string(this.id).isEmpty()) {
        const result = await sysCompany.add(data)
        this._resultChange(result, '添加成功!')
      } else {
        const result = await sysCompany.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>
