<template>
  <el-dialog :visible="innerVisible" :title="title" align="center" @close="handleClose" :close-on-click-modal="false">
    <el-form :rules="rules" :model="ruleForm" ref="ruleForm"  label-width="90px" size="mini">
      <el-form-item label="扫码枪">
        <el-input v-model="scanValue" type="textarea" placeholder="请在扫码完成后手动回车" @keyup.native.enter="handleEnterParse" />
      </el-form-item>
      <el-form-item label="发票类型" :prop="mapFields.invoiceType">
        <el-select v-model="ruleForm[mapFields.invoiceType]" style="width:100%" placeholder="发票类型">
          <el-option v-for="type in invTypes" :key="type.value" :value="type.value" :label="type.label"/>
        </el-select>
      </el-form-item>
      <el-form-item label="发票代码" :prop="mapFields.invoiceCode" v-if="!isAllelectric">
        <el-input v-model="ruleForm[mapFields.invoiceCode]" placeholder="发票代码" />
      </el-form-item>
      <el-form-item label="发票号码" :prop="mapFields.invoiceNumber">
        <el-input v-model="ruleForm[mapFields.invoiceNumber]"  placeholder="发票号码" />
      </el-form-item>
      <el-form-item label="税前金额" :prop="mapFields.beforeTax" v-if="!isAllelectric">
        <el-input v-model="ruleForm[mapFields.beforeTax]" placeholder="税前金额" />
      </el-form-item>
      <el-form-item label="税后金额" :prop="mapFields.afterTax" v-if="isAllelectric">
        <el-input v-model="ruleForm[mapFields.afterTax]" placeholder="税后金额" />
      </el-form-item>
      <el-form-item label="校验码" :prop="mapFields.checkNumber" v-if="!isAllelectric">
        <el-input v-model="ruleForm[mapFields.checkNumber]"  placeholder="校验码" />
      </el-form-item>

      <el-form-item label="开票日期" :prop="mapFields.openTime">
        <el-date-picker 
          v-model="ruleForm[mapFields.openTime]"  
          value-format="yyyy-MM-dd" 
          style="width:100%" 
          placeholder="开票日期" 
        />
      </el-form-item>

      <el-form-item style="display:flex;justify-content:flex-end">
        <el-button type="primary" @click="onSubmit" :loading="loading">保存</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import dayjs from "dayjs"
import { manuallyUploadRules, mapFields } from "./_template"
import { invoiceTypeList } from '@/assets/js/statusList'

/***
 * @props
 * 发票申请编号 invoiceNo
 * 发票状态 invoiceStatus
 * 发票类型 invoiceType
 * 发票号码 invoiceNumber
 * 发票代码 invoiceCode
 * 发票名称 invoiceName
 * 开票日期 openTime
 * 税前金额 beforeTax
 * 税后金额 afterTax
 * 校验码 checkNumber
*/

  const {
    invoiceCode: IC,
    invoiceType: IT,
    beforeTax: BT,
    openTime: OT,
    invoiceNumber:IN,
    checkNumber:CC
  } = mapFields

export default {
  props:[
    'visible',
    'updateItem', 
    'updateIndex',
    'isNormalType',
    'loading'
  ],
  computed:{
    invTypes(){
      const INT = this.isNormalType
      const ITS = invoiceTypeList.filter(({isNormal}) => (INT && isNormal) || (!INT && !isNormal))
      return ITS
    },
    isAllelectric(){
      const invoiceType = this.ruleForm[mapFields.invoiceType]
      const allelectries = ['5','6']
      return allelectries.includes(String(invoiceType))
    },
    isNormalTicket(){
      const invoiceType = this.ruleForm[mapFields.invoiceType]
      const specialTickets = ['1','3']
      return specialTickets.includes(String(invoiceType))
    },
    title(){
      const baseTitle = '发票'
      const prefix = this.updateItem ? '编辑' : '上传'
      return `${prefix}${baseTitle}`
    },
    rules(){
      const isNormalTicket = this.isNormalTicket
      return {
        ...manuallyUploadRules,
        [CC]:[{
          ...manuallyUploadRules[CC][0],
          // 普票必填校验码
          required: isNormalTicket
        }]
      }
    },
    innerVisible:{
      get(){
        return this.visible
      },
      set(newVal){
        this.$emit('update:visible',newVal)
      }
    }
  },
  watch:{
    visible:{
      handler(visible){
        if(!visible) return
        this.$nextTick(() => this.initData())
      },
      immediate: true
    }
  },
  data(){
    
    return {
      mapFields,
      scanValue: "",
      invoiceTypeList,
      ruleForm:{
        [IT]: "",
        [IC]: "",
        [BT]: "",
        [OT]: "",
        [IN]: "",
        [CC]: ""
      }
    }
  },
  methods:{
    handleClose(){
      this.innerVisible = false
      this.ruleForm = {
        [IT]: "", [IC]: "", [BT]: "",
        [OT]: "", [IN]: "", [CC]: ""
      }
    },

    handleEnterParse(){
      const _sV = this.scanValue

      /* 校验是否有中文逗号 **/
      if(_sV.indexOf('，') >= 0){
        this.scanValue = ""
        this.$message.error("不能包含中文逗号")
        return
      }
      
      const chunks = _sV.split(",")
      const correctLength = [8,9]
      
      if(!correctLength.includes(chunks.length)){
        this.scanValue = ""
        this.$message.error("扫码枪识别数据格式不正确,请重新扫描")
        return
      }

      const [
         _,
         iT, // 发票类型
         iC, // 发票代码
         iN, // 发票号码
         bT, // 税前金额
         oT, // 开票日期
         cC  // 校验码
        ] = chunks
      let _oT = ""
      
      if(oT){
        const yyyy = oT.slice(0, 4);
        const mm = oT.slice(4, 6);
        const dd = oT.slice(6);
        _oT = dayjs(`${yyyy}-${mm}-${dd}`).format("YYYY-MM-DD HH:mm:ss");
      }

      const _iT = invoiceTypeList.find(({sV}) => sV === String(iT))

      this.scanValue = ""
      this.ruleForm = {
        [BT]: bT,
        [IC]: iC,
        [CC]: cC,
        [IN]: iN,
        [OT]: _oT,
        [IT]: _iT ? _iT.value : "",
      }
    },
    initData(){
      const data = this.updateItem 
      ? JSON.parse(JSON.stringify(this.updateItem)) 
      : { [IT]: "", [IC]: "", [BT]: "", [OT]: "", [IN]: "", [CC]: "" }

      this.ruleForm = data
    },
    async onSubmit(){
      try{
        await this.$refs.ruleForm.validate()
        const { invoiceType } = this.ruleForm
        
        if(!this.invTypes.map(({value}) => value).includes(invoiceType)){
          this.$message.warning('上传发票的发票类型与申请发票的发票类型不一致')
          return
        }
        
        this.$emit("change", { data: this.ruleForm, index: this.updateIndex })
        // this.handleClose()
      }
        catch(err)
      {
        console.log(err)
      }
    }
  }
}
</script>
