<template>
  <div>
    <el-form
      inline
      :model="form"
      ref="form"
      class="dialog-info"
      label-width="120px">
      <el-form-item
        prop="name"
        verify
        label="名称">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item
        prop="category"
        verify
        :can-be-empty="projectName==='sanheguzhen'"
        label="类型">
        <el-select v-model="form.category">
          <el-option
            v-for="item in travelAgencyType"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        verify
        :can-be-empty="projectName==='sanheguzhen'"
        prop="shorthand"
        label="助记符">
        <el-input v-model="form.shorthand"></el-input>
      </el-form-item>
      <el-form-item
        label="折扣"
        verify
        :can-be-empty="projectName==='sanheguzhen'"
        prop="discount">
        <el-input-number
          v-model="form.discount"
          :step="0.1"
          :min="0"
          :max="10"
          :precision="1">
        </el-input-number>
      </el-form-item>

      <!-- <el-form-item
        label="限制信用额度"
        verify
        prop="prepayment_type">
        <el-switch
          v-model="form.prepayment_type"
          :active-value="1"
          :inactive-value="0">
        </el-switch>
      </el-form-item> -->

      <el-form-item
        label="信用额度"
        verify
        :can-be-empty="projectName==='sanheguzhen'"
        prop="prepayment_limit">
        <el-input-number
          :controls="false"
          v-model="form.prepayment_limit"
          :min="0"
          :precision="2">
        </el-input-number>
      </el-form-item>

      <el-form-item
        verify
        :can-be-empty="projectName==='sanheguzhen'"
        prop="valid_date"
        label="有效期至">
        <el-date-picker
          :editable="false"
          :clearable="false"
          v-model="form.valid_date"
          value-format="yyyy-MM-dd"
          type="date"
          :picker-options="dateOption"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item
        verify
        :can-be-empty="projectName==='sanheguzhen'"
        prop="areaArray"
        label="地区">
        <el-cascader
          v-model="form.areaArray"
          :options="provinceAndCityData">
        </el-cascader>
      </el-form-item>
      <el-form-item
        verify
        :can-be-empty="projectName==='sanheguzhen'"
        label="地址"
        prop="address">
        <el-input v-model="form.address"></el-input>
      </el-form-item>
      <el-form-item
        verify
        :can-be-empty="projectName==='sanheguzhen'"
        prop="contacts_name"
        label="联系人">
        <el-input v-model="form.contacts_name"></el-input>
      </el-form-item>
      <el-form-item
        :verify="verifyPhone"
        :can-be-empty="projectName==='sanheguzhen'"
        prop="contacts_phone"
        label="手机号码">
        <el-input v-model="form.contacts_phone"></el-input>
      </el-form-item>
      <el-form-item
        verify
        can-be-empty
        email
        label="邮箱"
        prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item
        prop="tax_name"
        label="发票抬头">
        <el-input v-model="form.tax_name"></el-input>
      </el-form-item>
      <el-form-item
        prop="tax_id"
        label="税号">
        <el-input v-model="form.tax_id"></el-input>
      </el-form-item>
      <el-form-item
        label="开户行"
        prop="opening_bank">
        <el-input v-model="form.opening_bank"></el-input>
      </el-form-item>
      <el-form-item
        label="对公账户"
        prop="account">
        <el-input v-model="form.account"></el-input>
      </el-form-item>
      <el-form-item
        prop="business_license"
        label="营业执照">
        <el-upload
          class="avatar-uploader"
          action=""
          :show-file-list="false"
          :auto-upload="false"
          :on-change="handleAvatarSuccess">
          <img
            v-if="form.business_license"
            :src="`data:image/jpeg;base64,${form.business_license}`"
            class="avatar">
          <i
            v-else
            class="el-icon-plus avatar-uploader-icon"
          ></i>
        </el-upload>
      </el-form-item>

      <!-- <el-form-item
        v-if="dialogType==='edit'"
        label="预付余额"
        prop="prepayment_amount">
        <b class="warning">{{ form.prepayment_amount }}</b>
      </el-form-item> -->
    </el-form>
    <div class="dialog-btn-wrap">
      <el-button
        v-if="dialogType === 'new'"
        @click="reset">
        重置
      </el-button>
      <el-button
        @click="submit"
        type="primary">
        保存
      </el-button>
    </div>
  </div>
</template>

<script>
import { apiUpdateTravelAgency, apiCreateTravelAgency } from '@/api/travelAgency'
import { provinceAndCityData, CodeToText, TextToCode } from 'element-china-area-data'
import { verifyPhone } from '@/utils/validate.js'
import moment from 'moment'
export default {
  props: {
    dialogType: {
      type: String,
      default: 'edit'
    },
    currentItem: {
      type: Object,
      default: () => {}
    },
    ticketTypeList: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    travelAgencyType () {
      return this.$store.state.app.travelAgencyType
    }
  },
  data () {
    return {
      projectName: process.env.VUE_APP_PROJECT,
      visible: false,
      areaProps: {
        label: 'name',
        value: 'name',
        children: 'children'
      },
      provinceAndCityData,
      dateOption: {
        disabledDate (theTime) {
          let startTime = moment().format('YYYY-MM-DD') + ' 00:00:00'
          return moment(theTime).isBefore(startTime)
        }
      },
      form: {
        name: '',
        shorthand: '',
        account: '',
        category: '',
        area: '',
        areaArray: [],
        discount: 10,
        contacts_name: '',
        contacts_phone: '',
        tax_name: '',
        valid_date: '',
        tax_id: '',
        cooperate_type: '',
        id: 0,
        is_rebate: 0,
        isUse: 0,
        is_valid: 1,
        buy_type: '',
        sort_value: 0,
        address: '',
        email: '',
        opening_bank: '',
        travelAgencyTicketType: [],
        prepayment_amount: 0,
        prepayment_limit: 0,
        prepayment_type: 1,
        business_license: ''
      }
    }
  },
  watch: {
    visible (val) {
      // 初始化表单
      if (val) {
        this.reset()
        if (!this.form.travelAgencyTicketType.length) {
          this.form.travelAgencyTicketType.push({
            ticketTypeId: '',
            discount: 10
          })
        }
        if (this.dialogType === 'edit' && this.currentItem) {
          this.form = Object.assign({}, this.form, JSON.parse(JSON.stringify(this.currentItem)))

          this.form.areaArray = this.textToCode(this.form.area)
        }
      }
    }
  },
  methods: {
    verifyPhone,
    codeToText (arr) {
      if (arr.length === 2) {
        return `${CodeToText[arr[0]]} ${CodeToText[arr[1]]}`
      } else {
        return `${CodeToText[arr[0]]}`
      }
    },
    textToCode (str) {
      let strArr = str.split(' ')
      if (strArr.length === 2) {
        return [TextToCode[strArr[0]].code, TextToCode[strArr[0]][strArr[1]].code]
      } else {
        return [TextToCode[strArr[0]].code]
      }
    },
    handleClose () {
      this.$parent.handleClose()
    },
    reset () {
      this.$refs.form.resetFields()
      this.form.area = []
      this.form.travelAgencyTicketType = []
    },
    submit () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.valid_date = this.formatEndTime(this.form.valid_date)
          this.form.area = this.codeToText(this.form.areaArray)
          this.form.travelAgencyTicketType = this.form.travelAgencyTicketType.filter(item => item.ticketTypeId)
          if (this.dialogType === 'new') {
            this.createAgency()
          } else if (this.dialogType === 'edit') {
            this.updateAgency()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    createAgency () {
      this.form.prepayment_amount = undefined

      apiCreateTravelAgency(this.form).then(res => {
        this.$message.success('添加成功')
        this.reset()
        this.handleClose()
        this.$emit('updateList')
        this.$store.dispatch('getAgencyList')
      })
    },
    updateAgency () {
      this.form.prepayment_amount = undefined

      apiUpdateTravelAgency(this.form).then(res => {
        this.$message.success('修改成功')
        this.reset()
        this.handleClose()
        this.$emit('updateList')
        this.$store.dispatch('getAgencyList')
      })
    },
    formatEndTime (time) {
      return moment(time).hour(23).minute(59).second(59).toDate()
    },
    handleAvatarSuccess (res, file) {
      const isJPG = res.raw.type === 'image/jpeg' || res.raw.type === 'image/png'
      // const isLt2M = res.raw.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('图片只能是 JPG或PNG 格式!')
        return
      }
      // if (!isLt2M) {
      //   this.$message.error('图片大小不能超过 2MB!')
      //   return
      // }
      let reader = new FileReader()
      reader.readAsDataURL(res.raw)
      reader.onload = (e) => {
        this.form.business_license = e.target.result.split(',')[1]
      }
    }
  }
}
</script>

<style scoped>

</style>
