<!--
  @description: 发票管理-发票信息新增-弹框
  @Modifier：dijia
  @routerPath:
  @date：2021/09/22
-->
<template>
  <el-dialog
    :visible.sync="data.dialog"
    title="发票管理"
    modal-append-to-body
    append-to-body
    width="920px"
    custom-class="shop_mall_dialog el-dialog__body-minHeight"
  >
    <el-form
      ref="ruleForm"
      :model="invoiceForm"
      :rules="rules"
      label-width="130px"
      label-position="left"
      style="padding:0 20px"
    >
      <el-row :gutter="30">
        <el-col :span="12">
          <!--新增 00 编辑 01 增加-->
          <el-form-item v-if="data.type==='01'" label="发票类型：" prop="invoiceType">
            <el-radio-group v-model="invoiceForm.invoiceType">
              <el-radio
                v-for="(item, index) in invoiceTypeList"
                :key="index"
                :label="item.typecode"
              >
                {{ item.typename }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <!--编辑-->
          <el-form-item v-if="data.type==='00'" label="发票类型：" prop="invoiceType">
            {{ filterDictText(invoiceTypeList, invoiceForm.invoiceType) }}
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="发票抬头：" prop="invoiceTitle">
            <gx-input
              v-model.trim="invoiceForm.invoiceTitle"
              gx-maxlength="varchar30"
              placeholder="请输入发票抬头"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="发票纳税税号："
            prop="taxpayerIdentificationNumber"
          >
            <gx-input
              v-model.trim="invoiceForm.taxpayerIdentificationNumber"
              gx-maxlength="varchar18"
              placeholder="请输入发票纳税税号"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!--  增值税专用票 显示-->
      <template v-if="invoiceForm.invoiceType === '01'">
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="注册电话：" prop="taxpayertel">
              <gx-input
                v-model.trim="invoiceForm.taxpayertel"
                gx-maxlength="varchar20"
                placeholder="请输入注册电话"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票开户银行：" prop="bankname">
              <gx-input
                v-model.trim="invoiceForm.bankname"
                gx-maxlength="varchar50"
                placeholder="请输入发票开户银行"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="注册地址：" prop="taxpayeraddr">
              <gx-input
                v-model.trim="invoiceForm.taxpayeraddr"
                gx-maxlength="varchar50"
                placeholder="请输入注册地址"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票银行账号：" prop="bankaccount">
              <gx-input
                v-model.trim="invoiceForm.bankaccount"
                gx-maxlength="varchar24"
                placeholder="请输入发票银行账号"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="默认发票">
            <el-checkbox v-model="invoiceForm.status">
              是
            </el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="60">
        <!--  增值税专用票 显示-->
        <el-col v-if="invoiceForm.invoiceType === '01'" :span="24">
          <el-form-item label="营业执照附件：" prop="shopInvoiceBusinessLicenseBase">
            <upload
              ref="upload"
              list-type="picture"
              :title="``"
              :data="upLoadData"
              :on-change="mainFileChange"
              :success="handleSuccess"
              :auto-delete="true"
              :auto-upload="true"
              :limit="1"
              accept="image/jpg,image/jpeg,image/png,image/gif"
              file-ref="fileRef"
              tip-text="上传附件格式 jpg，jpeg，png，gif "
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!--操作按钮-->
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="saveInvoiceBtn('ruleForm')">提 交</el-button>
      <el-button @click="data.dialog = false">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import upload from '@/components/common/updownload/upload.vue'
import { randomData } from '@/assets/js/utils/index'
/* 公用方法 */
import { bankCardNumber, phone } from '@/assets/js/validate'
import { saveInvoice, getInvoiceInfo, editInvoice } from '@/api/shoppingmall/order'
/* 公用方法*/
import { filterDictText } from '@/assets/js/utils'// 常用方法
export default {
  name: 'InvoiceAdd',
  components: {
    upload
  },
  props: {
    data: {
      type: Object,
      default: function() {
        return
      }
    }
  },
  data() {
    return {
      /* 普通类型发票 增值税专用票*/
      invoiceTypeList: [
        { typename: '普票类型发票', typecode: '00' },
        { typename: '增值税专用票', typecode: '01' }
      ],
      // 发票信息
      invoiceForm: {
        isDefault: '', // 00默认 其他：非默认
        auditOpinion: '',
        id: '',
        auditStatus: '',
        mailingName: '',
        mailingPhone: '',
        addressName: '',
        mailingAddress: '',
        invoiceTitle: '',
        invoiceType: '01',
        taxpayerIdentificationNumber: '',
        taxpayeraddr: '',
        bankname: '',
        bankaccount: '',
        shopInvoiceBusinessLicenseBase: '', // 营业执照附件
        shopInvoiceCorrespondenceBase: '', // 关联关系涵
        supplierAccount: '',
        provinceName: '',
        provinceCode: '',
        cityName: '',
        cityCode: '',
        areaName: '',
        status: false,
        areaCode: ''
      },
      upLoadData: {
        // 营业执照附件参数
        fileType: 'shop_invoice_business_license_base',
        bizId: ''
      },
      // 校验
      rules: {
        invoiceType: [{ required: true, message: '请选择发票类型', trigger: 'change' }],
        invoiceTitle: [{ required: true, message: '请输入发票抬头', trigger: 'change' }],
        taxpayerIdentificationNumber: [{ required: true, message: '请输入18位数值', trigger: 'change' }, { min: 18, max: 18, message: '税号长度必须为18位', trigger: 'blur' }],
        mailingName: [{ required: true, message: '请输入增值票收票人', trigger: 'change' }],
        mailingPhone: [{ required: true, validator: phone, message: '手机号码格式不正确', trigger: 'change' }],
        addressName: [{ required: true, message: '请选择所在地区', trigger: 'change' }],
        mailingAddress: [{ required: true, message: '请输入详细地址', trigger: 'change' }],
        taxpayertel: [{ required: true, validator: this.phoneAndTextCopy, trigger: 'change' }],
        bankname: [{ required: true, message: '请输入发票开户行', trigger: 'change' }],
        bankaccount: [{ required: true, validator: bankCardNumber, trigger: 'change' }],
        taxpayeraddr: [{ required: true, message: '请输入注册地址', trigger: 'change' }],
        shopInvoiceBusinessLicenseBase: [{ required: true, message: '请上传营业执照附件', trigger: 'change' }]
      }
    }
  },
  watch: {
    'ruleForm.region'(newValue) {
      // 通过父级传的只判断是编辑还是添加 00 编辑 01 添加
      if (newValue === '00') {
        this.type = false
      } else if (newValue === '01') {
        this.type = true
      }
    }
  },
  mounted() {
    // 编辑
    if (this.data.id && this.data.type === '00') {
      getInvoiceInfo(this.data.id).then(res => {
        if (res.data.isDefault === '00') {
          res.data.status = true
        } else {
          res.data.status = false
        }
        this.invoiceForm = JSON.parse(JSON.stringify(res.data))
        this.upLoadData.bizId = this.invoiceForm.shopInvoiceBusinessLicenseBase || randomData()
      }).catch(err => {
        throw new Error('修改发票失败' + err)
      })
    } else {
      this.upLoadData.bizId = randomData()
    }
  },
  methods: {
    filterDictText,
    //  提交
    saveInvoiceBtn(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.invoiceForm.status) {
            this.invoiceForm.isDefault = '00'
          } else {
            this.invoiceForm.isDefault = ''
          }
          this.invoiceForm.id = this.data.id
          const addressParams = JSON.parse(JSON.stringify(this.invoiceForm))
          delete addressParams.addressName
          // 00 编辑 01 新增
          if (this.data.type === '01') {
            this.saveInvoice(addressParams)
          } else {
            this.editInvoice(addressParams)
          }
        }
      })
    },
    // 新增保存
    saveInvoice(addressParams) {
      saveInvoice(addressParams).then(res => {
        this.$message.success('保存成功')
        this.data.dialog = false
        this.$emit('saveSuccess', true)
        this.$emit('updateList')
      }).catch(err => {
        throw new Error('添加发票失败' + err)
      })
    },
    // 编辑发票
    editInvoice(addressParams) {
      editInvoice(addressParams).then(res => {
        this.$message.success('保存成功')
        this.data.dialog = false
        this.$emit('saveSuccess', true)
      })
    },
    // 营业执照附件添加删除
    mainFileChange(file, fileList) {
      // 已经删除了营业执照
      if (fileList.length === 0) {
        this.invoiceForm.id = ''
        this.invoiceForm.shopInvoiceBusinessLicenseBase = ''
      }
    },
    // 营业执照附件信息成功的时触发
    handleSuccess(response) {
      this.invoiceForm.shopInvoiceBusinessLicenseBase = response.data.bizId
    },
    phoneAndTextCopy(rule, value, callback) {
      if (rule.required && !value) {
        return callback(new Error('不能为空'))
      }
      // 手机号||电话||400
      if (value.match(/(\+?86-?)?1(3|4|6|5|7|8|9)\d{9}/) || value.match(/((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))/) || value.match(/400(-\d{3,4}){2}/)) {
        // 校验通过
        callback()
      } else {
        // 校验未通过
        callback(new Error('联系电话格式不正确'))
      }
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.el-dialog__body-minHeight{
  .el-dialog__body {
    min-height: 300px;
  }
}
</style>
