<template>
  <div class="trems-content">
    <cy-info-title style="margin-top: 10px;">
      付款
    </cy-info-title>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-position="top"
      label-width="150px"
      class="rule-form-orange"
    >
      <el-form-item
        label="付款方式"
        prop="paymentWay"
      >
        <el-select
          v-model="ruleForm.paymentWay"
          placeholder="请选择付款方式"
          :disabled="disabled"
        >
          <el-option
            v-for="item in constant.payment_way"
            :key="item.dictCode"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="付款币种"
        prop="paymentCurrency"
      >
        <el-select
          v-model="ruleForm.paymentCurrency"
          placeholder="请选择付款币种"
          :disabled="disabled"
        >
          <el-option
            v-for="item in constant.currency_code"
            :key="item.dictCode"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="结算账期" prop="settlementCycle">
        <el-input
          v-model="ruleForm.settlementCycle"
          :disabled="disabled"
          placeholder="请输入结算账期"
        />
      </el-form-item>

      <div style="width: 100%; margin-top: 10px;">
        <cy-comm-table
          ref="payInfoTableRef"
          :columns="getColumns"
          :data="paymentInfo"
          :count="0"
        />
      </div>

      <cy-info-title style="margin-top: 10px;">收款账户信息</cy-info-title>
      <el-form-item label="账户名称" prop="accountName">
        <el-input
          v-model="ruleForm.accountName"
          :disabled="disabled"
          placeholder="请输入账户名称"
        />
      </el-form-item>
      <el-form-item label="银行账号" prop="accountNumber">
        <el-input
          v-model="ruleForm.accountNumber"
          :disabled="disabled"
          placeholder="请输入银行账号"
        />
      </el-form-item>
      <el-form-item label="开户行" prop="openingBank">
        <el-input
          v-model="ruleForm.openingBank"
          :disabled="disabled"
          placeholder="请输入开户行"
        />
      </el-form-item>
      <el-form-item label="Swift Code" prop="swiftCode">
        <el-input
          v-model="ruleForm.swiftCode"
          placeholder="请输入Swift Code"
          :disabled="disabled"
        />
      </el-form-item>

      <cy-info-title style="margin: 10px 0;">
        特殊约定（选填）
        <div v-if="$route.query.type !== 'see'" slot="right" style="display: flex; align-items: center;">
          <el-button type="text" @click="handleAddTitleInfo">添加</el-button>
        </div>
      </cy-info-title>
      <div style="width: 100%;">
        <cy-comm-table
          ref="commTable"
          :columns="getTitleInfoColumns"
          :data="titleInfo"
          :count="0"
        />
      </div>

      <cy-info-title>备注（选填）</cy-info-title>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="ruleForm.remark"
          :disabled="disabled"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  components: {
  },
  props: {
    detailsInfo: {
      type: Object,
      default: () => {}
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateAccountNumber = (rule, value, callback) => {
      const accountNumberReg = /^\d+$/
      if (!value) {
        return callback(new Error('银行账号不能为空'))
      }
      if (!accountNumberReg.test(value)) {
        return callback(new Error('请输入有效的银行账号 (只能输入数字)'))
      }
      callback()
    }
    const validateSwiftCode = (rule, value, callback) => {
      const swiftCodeRegex = /^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$/
      if (!value) {
        return callback(new Error('Swift Code不能为空'))
      }
      if (!swiftCodeRegex.test(value)) {
        return callback(new Error('请输入有效的 Swift Code (8 或 11 个字符)'))
      }
      callback()
    }
    return {
      ruleForm: {
        paymentWay: '',
        paymentCurrency: '',
        settlementCycle: '',
        accountName: '',
        accountNumber: '',
        openingBank: '',
        swiftCode: '',
        remark: ''
      },
      rules: {
        paymentWay: [
          { required: true, message: '请选择付款方式', trigger: 'change' }
        ],
        paymentCurrency: [
          { required: true, message: '请选择付款币种', trigger: 'blur' }
        ],
        settlementCycle: [
          { required: true, message: `请输入结账周期`, trigger: 'blur' }
        ],
        accountName: [
          { required: true, message: `请输入账户名称`, trigger: 'blur' }
        ],
        accountNumber: [
          { required: true, validator: validateAccountNumber, trigger: 'blur' }
        ],
        openingBank: [
          { required: true, message: `请输入开户行`, trigger: 'blur' }
        ],
        swiftCode: [
          { required: true, validator: validateSwiftCode, trigger: 'blur' }
        ]
      },
      paymentInfo: [
        {
          type: 1,
          paymentRatio: '',
          paymentName: '',
          paymentTime: '',
          paymentTerm: ''
        }
      ], // 付款信息表格
      columns: [
        {
          label: '序号',
          index: true
        },
        {
          label: '款项比例（%）',
          showTooltip: true,
          ruleRequired: true,
          width: '180',
          render: (h, row) => {
            return (
              <el-input
                v-model={ row.paymentRatio }
                disabled={ this.disabled }
                placeholder='请输入款项比例'
                onChange={ () => { this.payInfoRadioChange() } }
              ></el-input>
            )
          }
        },
        {
          label: '付款名称',
          showTooltip: true,
          ruleRequired: true,
          render: (h, row) => {
            return (
              <el-input
                v-model={ row.paymentName }
                disabled={ this.disabled }
                placeholder='请输入付款名称'
              ></el-input>
            )
          }
        },
        {
          label: '付款时点',
          showTooltip: true,
          ruleRequired: true,
          render: (h, row) => {
            return (
              <el-input
                v-model={ row.paymentTime }
                disabled={ this.disabled }
                placeholder='请输入，例如：合同签署后'
              ></el-input>
            )
          }
        },
        {
          label: '付款期限',
          showTooltip: true,
          ruleRequired: true,
          render: (h, row) => {
            return (
              <el-input
                v-model={ row.paymentTerm }
                disabled={ this.disabled }
                placeholder='请输入 (若为付款时点当天，则期限填为0) 天'
              ><template slot='append'>天</template></el-input>
            )
          }
        },
        {
          label: '操作',
          show: true,
          width: '100',
          render: (h, row, index) => {
            if (index === 0) {
              return (
                <div style='display: flex; cursor: pointer; color: #FE7D0B;' onClick={ () => { this.handleAddPayInfo() } }>
                  添加
                </div>
              )
            } else {
              return (
                <div style='display: flex;'>
                  <span style='cursor: pointer; color: #FE7D0B; margin-right:10px;' onClick={ () => { this.handleAddPayInfo() } }>添加</span>
                  <span style='cursor: pointer; color: #FE7D0B;' onClick={ () => { this.deletePayInfo(index) } }>删除</span>
                </div>
              )
            }
          }
        }
      ],
      titleInfo: [], // 特殊约定表格
      titleInfoColumns: [
        {
          label: '序号',
          index: true
        },
        {
          label: '条款标题',
          showTooltip: true,
          render: (h, row) => {
            return (
              <el-input
                v-model={ row.termTitle }
                disabled={ this.disabled }
                placeholder='请输入条款标题'
              ></el-input>
            )
          }
        },
        {
          label: '条款内容',
          showTooltip: true,
          render: (h, row) => {
            return (
              <el-input
                v-model={ row.content }
                disabled={ this.disabled }
                placeholder='请输入条款标题'
              ></el-input>
            )
          }
        },
        {
          label: '操作',
          show: true,
          render: (h, row, index) => {
            return (
              <div
                style='display: flex; justify-content: space-between;color: #FE7D0B;cursor: pointer;'
                onClick={ () => { this.deleteTitleInfo(index) } }
              >
                删除
              </div>
            )
          }
        }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'constant'
    ]),
    getColumns() {
      if (this.$route.query.type === 'see') {
        return this.columns.filter(item => item.label !== '操作')
      }
      return this.columns
    },
    getTitleInfoColumns() {
      if (this.$route.query.type === 'see') {
        return this.titleInfoColumns.filter(item => item.label !== '操作')
      }
      return this.titleInfoColumns
    }
  },
  watch: {
    detailsInfo: {
      handler(newV) {
        if (newV && Object.keys(newV).length) {
          const {
            paymentWay,
            paymentCurrency,
            settlementCycle,
            accountName,
            accountNumber,
            openingBank,
            swiftCode,
            remark,
            titleInfo,
            paymentInfo
          } = newV
          this.ruleForm = {
            paymentWay,
            paymentCurrency,
            settlementCycle,
            accountName,
            accountNumber,
            openingBank,
            swiftCode,
            remark
          }
          this.titleInfo = titleInfo || []
          this.paymentInfo = paymentInfo || []
          console.log(this.paymentInfo)
        }
      },
      immediate: true
    },
    'ruleForm.settlementCycle': {
      handler(val) {
        if (val) {
          this.settlementCycleChange()
        }
      },
      deep: true
    },
    paymentInfo: {
      handler(val) {
        if (val.length === 1) {
          val[0].paymentRatio = 100
        }
      },
      immediate: true
    }
  },
  created() {
    this.$store.dispatch('getConstant', ['currency_code', 'payment_way'])
  },
  methods: {
    async getParams(type) {
      this.paymentInfo.map(item => {
        item.paymentTerm = Number(item.paymentTerm)
        item.paymentRatio = Number(item.paymentRatio)
      })
      const params = {
        ...this.ruleForm,
        paymentInfo: this.paymentInfo,
        titleInfo: this.titleInfo
      }
      // 临时处理
      params.settlementCycle = Number(params.settlementCycle)

      return new Promise((resolve, reject) => {
        if (type === 'submit') {
          if (!this.validatePayInfo()) {
            return
          }

          // 付款款项表格的款项比例之和必须为100，且表格最大值的付款期限必须等于结算账期
          if (this.paymentInfo.length > 0) {
            const paymentRatioSum = this.paymentInfo.reduce((acc, cur) => acc + cur.paymentRatio, 0)

            if (paymentRatioSum !== 100) {
              this.$message.warning('付款款项表格的款项比例之和必须为100')
              return
            }

            const maxPaymentRatio = Math.max(...this.paymentInfo.map(item => item.paymentRatio))

            const find = this.paymentInfo.find(el => el.paymentRatio === maxPaymentRatio)

            if (find && find.paymentTerm !== params.settlementCycle) {
              this.$message.warning('付款款项表格款项比例最大值的付款期限必须等于结算账期')
              return
            }
          }

          this.$refs.ruleFormRef.validate(valid => {
            if (valid) {
              resolve(params)
            } else {
              reject()
              return false
            }
          })
        } else {
          resolve(params)
        }
      })
    },
    handleAddPayInfo() {
      this.paymentInfo.push({
        type: 1,
        paymentRatio: '',
        paymentName: '',
        paymentTime: '',
        paymentTerm: ''
      })
    },
    deletePayInfo(index) {
      this.paymentInfo.splice(index, 1)
    },
    deleteTitleInfo(index) {
      this.titleInfo.splice(index, 1)
    },
    validatePayInfo() {
      console.log(this.paymentInfo)
      let i = 0
      while (i < this.paymentInfo.length) {
        if (!this.paymentInfo[i].paymentRatio) {
          this.$message.warning(`请输入付款条件列表第${i + 1}行款项比例`)
          return false
        }
        if (!this.paymentInfo[i].paymentTime) {
          this.$message.warning(`请输入付款条件列表第${i + 1}行付款时点`)
          return false
        }
        if (!this.paymentInfo[i].paymentRatio) {
          this.$message.warning(`请输入付款条件列表第${i + 1}行款项比例`)
          return false
        }
        if (this.paymentInfo[i].paymentTerm === '') {
          this.$message.warning(`请输入付款条件列表第${i + 1}行付款期限`)
          return false
        } else if (this.paymentInfo[i].paymentTerm !== '') {
          if (isNaN(this.paymentInfo[i].paymentTerm)) {
            this.$message.warning(`请输入付款条件列表第${i + 1}行付款期限必须为数字`)
            return false
          }
        }
        i++
      }
      return true
    },
    handleAddTitleInfo() {
      this.titleInfo.push(
        {
          termTitle: '',
          content: '',
          type: 2
        }
      )
    },
    // 付款信息款项比例change
    payInfoRadioChange() {
      this.settlementCycleChange(true)
    },
    /**
     * 给付款表格填写结算账期--当表格数据为一条的时候直接赋值，为多条时候需要找到款项比例最大的
     * 然后给付款期限赋值
     */
    settlementCycleChange(clearFlag) {
      if (this.ruleForm.settlementCycle) {
        if (this.paymentInfo.length === 1) {
          this.paymentInfo[0].paymentTerm = this.ruleForm.settlementCycle
        }

        if (this.paymentInfo.length > 1) {
          const maxPaymentRatio = Math.max(...this.paymentInfo.map(item => item.paymentRatio))

          this.paymentInfo.forEach((el) => {
            if (clearFlag) {
              el.paymentTerm = ''
            }

            if (Number(el.paymentRatio) === maxPaymentRatio) {
              el.paymentTerm = this.ruleForm.settlementCycle
            }
          })
        }
      }
    }
  }
}
</script>

  <style lang="scss" scoped>
  .terms-content {
      padding: 10px 20px;
  }
  </style>
