<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>
        <el-col :span="24">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            status-icon
            :size="'small'"
            :rules="rulesThis"
            label-width="90px"
            class="demo-ruleForm"
          >
            <el-row>
              <el-col :span="1" style="padding: 20px 0 0 0">
                <ul class="tc fff">
                  <li>企</li>
                  <li>业</li>
                  <li>信</li>
                  <li>息</li>
                </ul>
              </el-col>
              <el-col :span="23" style="border-left: 1px solid #dcdfe6">
                <el-row>
                  <el-col :span="4">
                    <el-form-item label="法人" required>
                      {{ ruleForm.inv_legaler }}</el-form-item></el-col>
                  <el-col :span="4">
                    <el-form-item
                      label="营业执照"
                      prop="license_img"
                      class="activity-upload"
                    >
                      <div
                        class="btnupload"
                        style="position: relative; width: 28px; height: 28px"
                      >
                        <img
                          v-if="ruleForm.license_img"
                          v-viewer
                          :src="ruleForm.license_img"
                          class="avatar"
                        >
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="16">
                    <el-form-item label="企业名称" required>
                      {{ ruleForm.company }}
                    </el-form-item>
                  </el-col>

                  <el-col :span="24">
                    <el-row>
                      <el-col
                        :span="8"
                      ><el-form-item
                        label="纳税识别号"
                        required
                        label-width="100px"
                        style="width: 100%"
                      >
                        {{ ruleForm.inv_code }}
                      </el-form-item>
                      </el-col>
                      <el-col :span="7">
                        <el-form-item label="成立日期" required>
                          {{ ruleForm.inv_time }}
                        </el-form-item>
                      </el-col>

                      <el-col :span="9">
                        <el-form-item label="公司类型" required>
                          {{ ruleForm.type }}</el-form-item></el-col>
                    </el-row>
                  </el-col>

                  <el-col :span="18">
                    <el-form-item label="详细地址" required>
                      {{ ruleForm.addr }}
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="联系人" required>
                      {{ ruleForm.contactor }}
                    </el-form-item></el-col>

                  <el-col :span="24">
                    <el-form-item label="营业范围" required>
                      {{ ruleForm.inv_scope }}
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>

            <el-row style="border-top: 1px solid #dcdfe6">
              <el-col
                :span="1"
                style="
                  height: 120px;
                  padding: 20px 0 0 0;
                  border-right: 1px solid #dcdfe6;
                "
              >
                <ul class="tc sss">
                  <li>开</li>
                  <li>票</li>
                  <li>信</li>
                  <li>息</li>
                </ul>
              </el-col>
              <el-col :span="23" style="padding: 20px 0 0 0">
                <el-row>
                  <el-col :span="13">
                    <el-form-item label="公司抬头" prop="invoice_title">
                      <el-input
                        v-model="ruleForm.invoice_title"
                        placeholder="公司抬头"
                        :disabled="isDetail == '007'"
                        maxlength="100"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="11">

                    <el-form-item label="联系电话" prop="invoice_mobile">
                      <el-input
                        v-model="ruleForm.invoice_mobile"
                        placeholder="联系电话"
                        maxlength="100"
                        :disabled="isDetail == '007'"
                      >
                        <el-select slot="prepend" v-model="currentMobileMode" style="width:120px">
                          <el-option v-for="opt in options" :key="opt.value" :label="opt.label" :value="opt.value" />
                        </el-select>
                      </el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="13">

                    <el-form-item label="银行名称" prop="inv_bank">
                      <el-input
                        v-model="ruleForm.inv_bank"
                        placeholder="银行名称"
                        :disabled="isDetail == '007'"
                        maxlength="100"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="11">
                    <el-form-item label="银行卡号" prop="inv_bankNo">
                      <el-input
                        v-model="ruleForm.inv_bankNo"
                        placeholder="银行卡号"
                        maxlength="100"
                        :disabled="isDetail == '007'"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="24">
                    <el-form-item label="联系地址" prop="addr">
                      <el-input
                        v-model="ruleForm.inv_addr"
                        placeholder="联系地址"
                        maxlength="100"
                        :disabled="isDetail == '007'"
                      />
                    </el-form-item>
                  </el-col>

                  <div style="width: 100%; text-align: right">
                    <el-button
                      v-if="isDetail !== '007'"
                      type="primary"
                      :size="'small'"
                      @click="submitForm"
                    >保 存
                    </el-button>
                    <el-button :size="'small'" @click="showModelThis = false">{{
                      isDetail == "007" ? "关 闭" : "取 消"
                    }}</el-button>
                  </div>
                </el-row>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import asyncRequest from '@/apis/service/serviceParam/workCompany'
import resToken from '@/mixins/resToken'
import { isMobile, isPhone, invTime, isqzf, isqz, iszf, isz } from '@/utils/validate'
export default {
  name: 'WorkCompany',
  mixins: [resToken],
  props: ['showModel', 'id', 'isDetail'],
  data() {
    // const validatemobile = (rule, value, callback) => {
    //   if (value !== '') {
    //     if (isPhone(value) || isMobile(value)) {
    //       callback()
    //     } else {
    //       callback(new Error('联系电话格式不正确！'))
    //     }
    //   } else {
    //     callback(new Error('联系电话不能为空！'))
    //   }
    // }

    const basicRule = { required: true, trigger: 'blur' }

    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() >= Date.now()
        }
      },
      currentMobileMode: '0',
      supplier_name: '',
      accountNames: '',
      loading: false,
      title: '添加业务企业',
      showModelThis: this.showModel,
      ruleForm: {
        id: '',
        company: '', // 公司名称
        type: '', //	公司类型
        inv_code: '', //	纳税识别号
        inv_legaler: '', //	法人
        inv_time: '', // 注册日期
        inv_addr: '', // 注册地址
        inv_bank: '', //	银行
        inv_bankNo: '', //	银行账户
        contactor: '', //		联系人
        invoice_mobile: '', //	联系人电话
        addr: '', //		联系地址
        inv_scope: '', //	经营范围
        license_img: '', //	营业执照
        invoice_title: ''
      },
      rulesThis: this.rules,
      options: [
        {
          value: '0',
          label: '区-固-分',
          rule: {
            ...basicRule,
            validator(rule, value, callback) {
              if (!value) {
                return callback(new Error('联系电话不能为空！'))
              }

              if (!isqzf(value)) {
                callback(new Error('联系电话格式不正确！'))
              } else {
                callback()
                return true
              }
            }
          }
        },
        {
          value: '1',
          label: '区-固',
          rule: {
            ...basicRule,
            validator(rule, value, callback) {
              if (!value) {
                return callback(new Error('联系电话不能为空！'))
              }

              if (!isqz(value)) {
                callback(new Error('联系电话格式不正确！'))
              } else {
                callback()
                return true
              }
            }
          }
        },
        {
          value: '2',
          label: '固-分',
          rule: {
            ...basicRule,
            validator(rule, value, callback) {
              if (!value) {
                return callback(new Error('联系电话不能为空！'))
              }

              if (!iszf(value)) {
                callback(new Error('联系电话格式不正确！'))
              } else {
                callback()
                return true
              }
            }
          }
        },
        {
          value: '3',
          label: '固',
          rule: {
            ...basicRule,
            validator(rule, value, callback) {
              if (!value) {
                return callback(new Error('联系电话不能为空！'))
              }

              if (!isz(value)) {
                callback(new Error('联系电话格式不正确！'))
              } else {
                callback()
                return true
              }
            }
          }
        },
        {
          value: '4',
          label: '手机号',
          rule: {
            ...basicRule,
            validator(rule, value, callback) {
              if (!value) {
                callback(new Error('联系电话不能为空！'))
              }

              if (!isMobile(value)) {
                callback(new Error('联系电话格式不正确！'))
              } else {
                callback()
                return true
              }
            }
          }
        }
      ],
      rules: {
        inv_bank: [
          {
            required: true,
            message: '银行名称不能为空！',
            trigger: 'blur'
          }
        ],
        inv_bankNo: [
          {
            required: true,
            message: '银行卡号不能为空！',
            trigger: 'blur'
          }
        ],

        mobile: [
          {
            ...basicRule,
            validator(rule, value, callback) {
              if (!value) {
                return callback(new Error('联系电话不能为空！'))
              }

              if (!isqzf(value)) {
                callback(new Error('联系电话格式不正确！'))
              } else {
                callback()
                return true
              }
            }
          }
        ],
        invoice_title: [{ required: true, message: '公司抬头不能为空!', trigger: 'blur' }],
        addr: [{ required: true, message: '联系地址不能为空！', trigger: 'blur' }]
      }
    }
  },
  watch: {
    showModel: function(val) {
      this.showModelThis = val
      if (val) {
        this.initForm()
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit('cancel')
      }
    },
    currentMobileMode() {
      this.$set(this.rulesThis.invoice_mobile, '0', this.options[this.currentMobileMode].rule)
    }
  },
  methods: {
    async initForm() {
      this.supplier_name = ''
      this.loading = true
      if (this.isDetail == '007') {
        this.title = '业务企业详情'
        this.rulesThis = {}
        await this.resetForm()
        await this.initData()
      } else {
        this.title = '修改业务企业'
        this.rulesThis = this.rules
        await this.resetForm()
        await this.initData()
      }
      this.loading = false
    },
    type_search_change(e) {
      const { id, code, label } = e
      if (id) {
        this.ruleForm.type = id
      } else {
        this.ruleForm.type = ''
      }
      this.$refs.ruleForm.validateField('type')
    },

    async initData() {
      const res = await asyncRequest.detail({ companyNo: this.id })
      if (res && res.code === 0 && res.data) {
        const {
          id,
          company, // 公司名称
          company_type, //	公司类型
          inv_code, //	纳税识别号
          inv_legaler, //	法人
          inv_time, // 注册日期
          inv_addr, // 注册地址
          inv_bank, //	银行
          inv_bankNo, //	银行账户
          contactor, //		联系人
          invoice_mobile, //	联系人电话
          addr, //		联系地址
          inv_scope, //	经营范围
          license_img, //	营业执照
          invoice_title
        } = res.data

        const index = this.options.findIndex(({ rule }) => rule.validator('', invoice_mobile, () => {}))
        this.currentMobileMode = String(index)

        this.ruleForm = {
          id: id || '',
          company: company || '', // 公司名称
          type: company_type || '', //	公司类型
          inv_code: inv_code || '', //	纳税识别号
          inv_legaler: inv_legaler || '', //	法人
          inv_time: invTime(inv_time) || '', // 注册日期
          inv_addr: inv_addr || '', // 注册地址
          inv_bank: inv_bank || '', //	银行
          inv_bankNo: inv_bankNo || '', //	银行账户
          contactor: contactor || '', //		联系人
          invoice_mobile: invoice_mobile || '', //	联系人电话
          addr: addr || '', //		联系地址
          inv_scope: inv_scope || '', //	经营范围
          license_img: license_img || '', //	营业执照
          invoice_title: invoice_title || ''
        }
      } 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.ruleForm = {
            id: '',
            company: '', // 公司名称
            type: '', //	公司类型
            inv_code: '', //	纳税识别号
            inv_legaler: '', //	法人
            inv_time: '', // 注册日期
            inv_addr: '', // 注册地址
            inv_bank: '', //	银行
            inv_bankNo: '', //	银行账户
            contactor: '', //		联系人
            invoice_mobile: '', //	联系人电话
            addr: '', //		联系地址
            inv_scope: '', //	经营范围
            license_img: '' //	营业执照
          }
        }
      })
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          if (this.loading) {
            return
          }
          this.loading = true
          const { code, inv_bank, inv_bankNo, inv_addr, invoice_mobile, id, invoice_title } = this.ruleForm

          const model = {
            id,
            code,
            inv_bank,
            inv_bankNo,
            inv_addr,
            invoice_mobile,
            invoice_title
          }
          const res = await asyncRequest.update(model)

          this.loading = false
          if (res && res.code === 0) {
            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
        }
      })
    },
    // 判断图片规格
    beforeAvatarUpload(file) {
      let isJPG = false
      let isLt2M = false
      if (file) {
        if (
          file.type === 'image/jpg' ||
          file.type === 'image/png' ||
          file.type === 'image/jpeg'
        ) {
          isJPG = true
        }
        isLt2M = file.size / 1024 / 1024 < 1
        if (!isJPG) {
          this.$message.error('图片格式不正确！')
        }
        if (!isLt2M) {
          this.$message.error('图片大小不能超过 1MB!')
        }
      }

      return isJPG && isLt2M
    },
    // 图片上传失败
    UploadErrorEvent(res) {
      if (res !== 'break') {
        this.$message.error('图片上传失败!')
        this.ruleForm.license_img = ''
        this.$refs.ruleForm.validateField('license_img')
      }
    },
    // 图片上传成功
    async UploadSuccessEvent(data) {
      const { url } = data
      if (url === 'noToken') {
        await this.logout()
      } else {
        this.ruleForm.license_img = url
        this.$message.success('图片上传成功!')
        this.$refs.ruleForm.validateField('license_img')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.workCompany {
  .fff,
  .sss {
    // border-right: 1px solid #DCDFE6;
    box-sizing: border-box;
    li {
      line-height: 20px;
      font-size: 16px;
      font-weight: bold;
      height: 20px;
    }
  }
  .fff {
    padding: 115px 0 0 0;
  }
}
</style>
