<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 invoiceTypeList" :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">保存</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
*/

export default {
  props:['visible','updateItem','updateIndex'],
  computed:{
    isAllelectric(){
      const invoiceType = this.ruleForm[mapFields.invoiceType]
      const allelectries = ['5','6']
      return allelectries.includes(invoiceType)
    },
    isNormalTicket(){
      const invoiceType = this.ruleForm[mapFields.invoiceType]
      const specialTickets = ['1','3']
      return specialTickets.includes(invoiceType)
    },
    title(){
      const base = '发票'
      console.log(this.updateItem)
      const prefix = this.updateItem ? '编辑' : '上传'
      return `${prefix}${base}`
    },
    rules(){
      const isNormalTicket = this.isNormalTicket
      return {
        ...manuallyUploadRules,
        [mapFields.checkNumber]:[{
          ...manuallyUploadRules[mapFields.checkNumber][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 {
      scanValue:"",
      invoiceTypeList,
      mapFields,
      ruleForm:{
        [mapFields.invoiceType]:"",
        [mapFields.invoiceCode]:"",
        [mapFields.beforeTax]:"",
        [mapFields.openTime]: "",
        [mapFields.invoiceNumber]:"",
        [mapFields.checkNumber]:""
      }
    }
  },
  methods:{
    handleClose(){
      this.innerVisible = false
      this.ruleForm = {
        [mapFields.invoiceType]:"",
        [mapFields.invoiceCode]:"",
        [mapFields.beforeTax]:"",
        [mapFields.openTime]: "",
        [mapFields.invoiceNumber]:"",
        [mapFields.checkNumber]:""
      }
    },
    handleEnterParse(evt){
      /* 校验是否有中文逗号 **/
      if(this.scanValue.indexOf('，') >= 0){
        this.scanValue = ""
        this.$message.error("不能包含中文逗号")
        return
      }
      
      const result = this.scanValue.split(",")
      if(result.length !== 8 && result.length !== 9){
        this.scanValue = ""
        this.$message.error("扫码枪识别数据格式不正确,请重新扫描")
      }
      
      const [_1,invoiceType,invCode,invNumber,subtotal_amount,open_time,checkNumber] = result
      let _open_time = ""
      
      if(open_time){
        const year = open_time.slice(0, 4);
        const month = open_time.slice(4, 6);
        const day = open_time.slice(6);
        _open_time = dayjs(`${year}-${month}-${day}`).format("YYYY-MM-DD HH:mm:ss");
      }

      // 1,01,3,4,5,6,7,8,9

      const invoice = invoiceTypeList.find(({scanValue}) => scanValue === String(invoiceType))
      

      console.log(invoice)
      this.scanValue = ""
      // const { invoice } = mapPropertys
      this.ruleForm = {
        [mapFields.invoiceType]:invoice ? invoice.value : "",
        [mapFields.invoiceCode]:invCode,
        [mapFields.beforeTax]:subtotal_amount,
        [mapFields.openTime]: _open_time,
        [mapFields.invoiceNumber]:invNumber,
        [mapFields.checkNumber]:checkNumber
      }
    },
    initData(){
      const data = this.updateItem ? JSON.parse(JSON.stringify(this.updateItem)) :{
        [mapFields.invoiceType]:"",
        [mapFields.invoiceCode]:"",
        [mapFields.beforeTax]:"",
        [mapFields.openTime]: "",
        [mapFields.invoiceNumber]:"",
        [mapFields.checkNumber]:""
      }
      this.ruleForm = data
    },
    async onSubmit(){
      try{
        await this.$refs.ruleForm.validate()
        this.$emit("change",{
          data:this.ruleForm,
          index:this.updateIndex
        })
        this.handleClose()
        // thiis
      }catch(err){
        console.log(err)
      }
    }
  }
}
</script>
