<template>
  <el-dialog
    :visible.sync="visible"
    v-bind="modalOptions"
  >
    <el-form
      ref="formData"
      :model="formData"
      :rules="formRules"
      size="mini"
      label-suffix=":"
      label-width="150px"
    >
      <!-- <p class="card">原绑定信息</p>
        <el-form-item label="原持卡人姓名" prop="cardName">
        <el-input v-model="formData.cardName" />
        </el-form-item>
        <el-form-item label="原银行卡号" prop="oldCardNumber">
        <el-input v-model="formData.oldCardNumber" />
        </el-form-item>
        <p class="card">新绑定信息</p> -->
      <el-form-item label="账户类型" prop="bankType">
        <el-radio-group v-model="formData.bankType">
          <el-radio :label="1">对公</el-radio>
          <el-radio :label="2">对私</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="持卡人姓名" prop="cardName">
        <el-input
          v-model="formData.cardName" maxlength="20"
          @blur="(e) => e.target.value.replace(cardNameReg, '')"
        />
      </el-form-item>
      <el-form-item label="卡号" prop="cardNumber">
        <el-input v-model="formData.cardNumber" maxlength="19" />
      </el-form-item>
      <el-form-item label="银行" prop="bank">
        <el-select v-model="formData.bank" filterable placeholder="请选择所属银行">
          <el-option v-for="item in bankList" :key="item.dictName" :label="item.dictName" :value="item.dictId" />
        </el-select>
      </el-form-item>
      <el-form-item label="注册手机号" prop="phone">
        <el-input v-model="formData.phone" maxlength="11" style="width: 120px;" />
        <el-button style="margin-left: 10px;" type="primary" :loading="codeLoading" @click="handleSendCode(formData.phone)">
          <span v-if="!codeLoading">获取验证码</span>
          <span v-else>{{ codeCount }} s</span>
        </el-button>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input
          v-model="formData.code" oninput="value=value.replace(/[^\d]/g,'')" maxlength="6"
          style="width: 120px;"
        />
      </el-form-item>
      <el-form-item v-if="formData.bankType === 1" label="开户行所在省市" prop="city">
        <el-cascader
          v-model="regionArrDialog" :props="regionProps" size="large" placeholder="请选择区域"
          @change="((formData.province = regionArrDialog[0]) || true) && (formData.city = regionArrDialog[1])"
        ></el-cascader>
        <!-- <div v-if="formData.areaId">已选ID：{{ formData.areaId }}</div> -->
      </el-form-item>
      <el-form-item v-if="formData.bankType === 1" label="开户行详细名称" prop="bankName">
        <el-input v-model="formData.bankName" placeholder="请输入开户行详细名称" />
      </el-form-item>
      <el-form-item v-if="formData.bankType === 1" label="开户行的联行号" prop="unionBank">
        <el-input v-model="formData.unionBank" placeholder="请输入支付行号" />
      </el-form-item>
      <el-form-item v-if="formData.bankType === 1" label="银行代码" prop="bankCode">
        <el-select v-model="formData.bankCode" size="mini" placeholder="请选择银行代码">
          <el-option v-for="(item, index) in bankCodeList" :key="index" :label="`${item.id}（${item.name}）`" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" @click="handleClose">取 消</el-button>
      <el-button type="primary" size="mini" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getSelect, getCode, bankUpdate, bankAdd } from '@/api/account'
import { searchParentId } from '@/api/threeSelection'
import bankCodeData from '../bankCode.json'

export default {
  name: 'EditModal',
  components: {
  },
  data() {
    return {
      modalOptions: {
        closeOnClickModal: false,
        width: '820px',
        title: ''
      },
      visible: false,
      formData: {
        id: '',
        // oldCardNumber: '',
        // oldPhone: '',
        cardName: '',
        cardNumber: '',
        bank: '',
        phone: '',
        code: '',
        bankType: '',
        province: '',
        city: '',
        bankName: '',
        unionBank: '',
        bankCode: ''
      },
      formRules: {
        cardName: [
          { required: true, message: '请输入持卡人姓名', trigger: 'blur' }
        ],
        cardNumber: [
          { required: true, message: '请输入正确银行卡号，卡号必须为以数字开头，10~19位的卡号！！！', trigger: 'blur' }
        ],
        phone: [ { required: true, message: '请输入手机号', trigger: 'blur' } ],
        code: [ { required: true, message: '请输入验证码', trigger: 'blur' } ],
        bank: [ { required: true, message: '请输入选择银行', trigger: 'blur' } ],
        // oldCardNumber: [
        //   { required: true, message: '请输入原银行卡号', trigger: 'blur' }
        // ],
        bankType: [ { required: true, message: '请选择账户类型' } ],
        city: [ { required: true, message: '请选择开户行所在省市' } ],
        bankName: [ { required: true, message: '请输入开户行详细名称' } ],
        unionBank: [ { required: true, message: '请输入开户行的联行号' } ],
        bankCode: [ { required: true, message: '请输入银行代码' } ]
      },
      cardNameReg: /[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、' ']/g,
      bankList: [],
      codeTimer: '',
      codeLoading: false,
      codeCount: '',
      regionArrDialog: [],
      regionProps: {
        lazy: true,
        label: 'name',
        value: 'shortName',
        lazyLoad(node, resolve) {
          const { level, value, data } = node
          if (level === 0) {
            searchParentId({ parentId: 0 }).then((res) => {
              resolve(res.data)
            })
          } else if (level != 0) {
            searchParentId({ parentId: data.id }).then((res) => {
              resolve(res.data.map((item) => {
                item.leaf = level === 1
                return item
              }))
            })
          }
        }
      },
      bankCodeList: bankCodeData.data
    }
  },
  watch: {
    'formData.bankType': {
      deep: true,
      handler(val) {
        if (val === 1) {
          this.formRules.city = [ { required: true, message: '请选择开户行所在省市' } ]
          this.formRules.bankName = [ { required: true, message: '请输入开户行详细名称' } ]
          this.formRules.unionBank = [ { required: true, message: '请输入开户行的联行号' } ]
          this.formRules.bankCode = [ { required: true, message: '请输入银行代码' } ]
        } else {
          this.formRules.city = []
          this.formRules.bankName = []
          this.formRules.unionBank = []
          this.formRules.bankCode = []
        }
      }
    }
  },
  methods: {
    handleClose() {
      this.visible = false
    },
    // 获取验证码
    async handleSendCode(phone) {
      if (phone === '') {
        this.$message.error('请填写电话号码')
        return
      } else if (!/^1[3-9]\d{9}$/.test(phone)) {
        this.$message({
          message: '请输入正确手机号',
          type: 'warning'
        })
        return false
      }
      if (!this.codeTimer) {
        const res = await getCode({ phone })
        if (res.code === '') {
          this.$message({
            message: '发送成功，请注意查看手机短信',
            type: 'success'
          })
        }
        this.codeLoading = true
        this.codeCount = 60
        this.codeTimer = setInterval(() => {
          if (this.codeCount > 0 && this.codeCount <= 60) {
            this.codeCount--
          } else {
            clearInterval(this.codeTimer) // 清除定时器
            this.codeTimer = null
            this.codeLoading = false
          }
        }, 1000)
      }
    },
    async getBankList() {
      const res = await getSelect({ dictName: '所属银行' })
      this.bankList = res.data
    },
    initList() {
      this.getBankList()
    },
    handleOpen(params = {}) {
      this.modalOptions.title = params.id ? '更换银行卡' : '绑定银行卡'
      this.formData = Object.assign(this.$options.data().formData, params)
      if (this.formData.province && this.formData.city) this.regionArrDialog = [this.formData.province, this.formData.city]
      else if (this.formData.province) this.regionArrDialog = [this.formData.province, '']
      this.visible = true
      this.initList()
      if (params.id) { // 关联店铺Id
        // this.getInfo(params.id)
      } else {
        this.$refs.formData && this.$refs.formData.resetFields()
      }
    },
    async getInfo(id) {
      const loading = this.$loading({ text: '加载中' })
      try {
        const res = await xxx({ id })
        this.formData = Object.assign(this.$options.data().formData, res.data, {
          id: res.data.id || ''
        })
        this.$nextTick(() => {
          this.$refs.formData && this.$refs.formData.validate()
        })
      } finally {
        loading.close()
      }
    },
    handleSubmit() {
      console.log(this.formData)
      this.$refs.formData.validate(async (valid) => {
        if (valid) {
          const loading = this.$loading({ text: '提交中，请稍候……' })
          try {
            const { ...otps } = this.formData
            const params = {
              ...otps
            }
            this.formData.id ? await bankUpdate(params) : await bankAdd(params)
            loading.close()
            this.$message({ message: `${this.formData.id ? '编辑' : '添加'}成功!`, type: 'success' })
            this.$emit('success')
            this.visible = false
          } catch (e) {
            loading.close()
          } finally {
            loading.close()
          }
        } else {
          this.$message({ message: '请输入相关信息', type: 'warning' })
          return false
        }
      })
    }
  }
}
</script>

