<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item prop="recipientName">
          <template slot="label">{{ pubT('queryRecipientName') }}</template>
          <el-input
            v-model="queryParams.recipientName"
            :placeholder="pubT('queryRecipientNamePh')"
            clearable
            style="width: 180px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="subsidyType">
          <template slot="label">{{ pubT('querySubsidyType') }}</template>
          <el-select v-model="queryParams.subsidyType" :placeholder="$t('policy.common.pleaseSelect')" clearable style="width: 140px">
            <el-option
              v-for="item in subsidyTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="startDate">
          <template slot="label">{{ pubT('queryStartDate') }}</template>
          <el-date-picker
            v-model="queryParams.startDate"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="$t('policy.common.pleaseSelect')"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item prop="endDate">
          <template slot="label">{{ pubT('queryEndDate') }}</template>
          <el-date-picker
            v-model="queryParams.endDate"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="$t('policy.common.pleaseSelect')"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('policy.common.search') }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('policy.common.reset') }}</el-button>
          <el-button
            v-hasPermi="['industryPolicy:subsidyRecord:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ $t('policy.common.add') }}</el-button>
          <el-button
            v-hasPermi="['industryPolicy:subsidyRecord:remove']"
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="!ids.length"
            @click="handleDeleteBatch"
          >{{ $t('policy.common.delete') }}</el-button>
          <!-- 导出功能暂未开放
          <el-button
            v-hasPermi="['industryPolicy:subsidyRecord:export']"
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
          >{{ $t('policy.common.export') }}</el-button>
          -->
        </el-form-item>
      </el-form>
    </el-card>

    <br />

    <el-card shadow="never">
      <el-table v-loading="loading" :data="tableList" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column :label="pubT('colProjectName')" prop="subsidyProjectName" align="center" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column :label="pubT('colSubsidyType')" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ typeLabel(scope.row.subsidyType) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="pubT('colRecipientName')" prop="recipientName" align="center" width="110" :show-overflow-tooltip="true" />
        <el-table-column :label="pubT('colAmount')" align="center" width="110">
          <template slot-scope="scope">
            <span>{{ formatAmount(scope.row.subsidyAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="pubT('colGrantDate')" prop="grantDate" align="center" width="110" />
        <el-table-column :label="pubT('colPhone')" prop="contactPhone" align="center" width="120" />
        <el-table-column :label="$t('policy.common.colCreate')" align="center" width="160">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime ? parseTime(scope.row.createTime) : $t('policy.status.dash') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('policy.common.colOp')" align="center" class-name="small-padding fixed-width" width="200">
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['industryPolicy:subsidyRecord:query']"
              type="text"
              size="mini"
              @click="handleView(scope.row)"
            >{{ $t('policy.common.view') }}</el-button>
            <el-button
              v-hasPermi="['industryPolicy:subsidyRecord:edit']"
              type="text"
              size="mini"
              @click="handleEdit(scope.row)"
            >{{ $t('policy.common.edit') }}</el-button>
            <el-button
              v-hasPermi="['industryPolicy:subsidyRecord:remove']"
              type="text"
              size="mini"
              @click="handleDelete(scope.row)"
            >{{ $t('policy.common.delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <el-dialog :title="dialogTitle" :visible.sync="open" width="620px" append-to-body @close="cancel">
      <el-form :key="formKey" ref="form" :model="form" label-width="110px">
        <el-form-item prop="subsidyProjectName" :rules="formRules.subsidyProjectName">
          <template slot="label">{{ pubT('formProjectName') }}</template>
          <el-input v-model="form.subsidyProjectName" :placeholder="pubT('phProjectName')" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item prop="subsidyType" :rules="formRules.subsidyType">
          <template slot="label">{{ pubT('formSubsidyType') }}</template>
          <el-select v-model="form.subsidyType" :placeholder="$t('policy.common.pleaseSelect')" style="width: 100%">
            <el-option
              v-for="item in subsidyTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="recipientName" :rules="formRules.recipientName">
          <template slot="label">{{ pubT('formRecipientName') }}</template>
          <el-input v-model="form.recipientName" :placeholder="pubT('phRecipientName')" maxlength="10" show-word-limit />
        </el-form-item>
        <el-form-item prop="idCard" :rules="formRules.idCard">
          <template slot="label">{{ pubT('formIdCard') }}</template>
          <el-input v-model="form.idCard" :placeholder="pubT('phIdCard')" maxlength="18" />
        </el-form-item>
        <el-form-item prop="contactPhone" :rules="formRules.contactPhone">
          <template slot="label">{{ pubT('formContactPhone') }}</template>
          <el-input v-model="form.contactPhone" :placeholder="pubT('phContactPhone')" maxlength="11" />
        </el-form-item>
        <el-form-item prop="bankAccount" :rules="formRules.bankAccount">
          <template slot="label">{{ pubT('formBankAccount') }}</template>
          <el-input v-model="form.bankAccount" :placeholder="pubT('phBankAccount')" maxlength="19" />
        </el-form-item>
        <el-form-item prop="subsidyAmount" :rules="formRules.subsidyAmount">
          <template slot="label">{{ pubT('formAmount') }}</template>
          <el-input-number
            v-model="form.subsidyAmount"
            :placeholder="pubT('phAmount')"
            :min="0.01"
            :precision="2"
            :step="100"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item prop="grantDate" :rules="formRules.grantDate">
          <template slot="label">{{ pubT('formGrantDate') }}</template>
          <el-date-picker
            v-model="form.grantDate"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="$t('policy.common.pleaseSelect')"
            :picker-options="grantDatePickerOptions"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item prop="remark">
          <template slot="label">{{ pubT('formRemark') }}</template>
          <el-input v-model="form.remark" type="textarea" :rows="2" maxlength="500" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('policy.common.ok') }}</el-button>
        <el-button @click="cancel">{{ $t('policy.common.cancel') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="$t('policy.common.viewTitle')" :visible.sync="viewOpen" width="600px" append-to-body>
      <el-form label-width="110px" size="small">
        <el-form-item :label="pubT('formProjectName')">
          <span>{{ viewRow.subsidyProjectName }}</span>
        </el-form-item>
        <el-form-item :label="pubT('formSubsidyType')">
          <span>{{ typeLabel(viewRow.subsidyType) }}</span>
        </el-form-item>
        <el-form-item :label="pubT('formRecipientName')">
          <span>{{ viewRow.recipientName }}</span>
        </el-form-item>
        <el-form-item :label="pubT('formIdCard')">
          <span>{{ viewRow.idCard || $t('policy.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="pubT('formContactPhone')">
          <span>{{ viewRow.contactPhone || $t('policy.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="pubT('formBankAccount')">
          <span>{{ viewRow.bankAccount || $t('policy.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="pubT('formAmount')">
          <span>{{ formatAmount(viewRow.subsidyAmount) }}</span>
        </el-form-item>
        <el-form-item :label="pubT('formGrantDate')">
          <span>{{ viewRow.grantDate || $t('policy.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="pubT('formRemark')">
          <span>{{ viewRow.remark || $t('policy.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="pubT('viewCreateBy')">
          <span>{{ viewRow.createBy || $t('policy.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="$t('policy.common.colCreate')">
          <span>{{ viewRow.createTime ? parseTime(viewRow.createTime) : $t('policy.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="pubT('viewUpdateBy')">
          <span>{{ viewRow.updateBy || $t('policy.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="pubT('viewUpdateTime')">
          <span>{{ viewRow.updateTime ? parseTime(viewRow.updateTime) : $t('policy.status.dash') }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">{{ $t('policy.common.close') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import policyPublicityLocaleMixin from "@/mixins/policyPublicityLocaleMixin"
import {
  listSubsidyRecord,
  getSubsidyRecord,
  addSubsidyRecord,
  updateSubsidyRecord,
  delSubsidyRecord
} from "@/api/policy/subsidyRecord"

const ID_CARD_REG = /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/
const PHONE_REG = /^1[3-9]\d{9}$/
const BANK_REG = /^\d{16,19}$/

export default {
  name: "PolicySubsidyRecord",
  mixins: [policyPublicityLocaleMixin],
  data() {
    return {
      pubNs: "subsidyRecord",
      loading: false,
      open: false,
      viewOpen: false,
      viewRow: {},
      dialogEdit: false,
      formKey: 0,
      total: 0,
      tableList: [],
      ids: [],
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        recipientName: undefined,
        subsidyType: undefined,
        startDate: undefined,
        endDate: undefined
      },
      form: {}
    }
  },
  computed: {
    dialogTitle() {
      return this.dialogEdit ? this.pubT("dialogEdit") : this.pubT("dialogAdd")
    },
    subsidyTypeOptions() {
      return [1, 2, 3].map((value) => ({ label: this.pubT("type" + value), value }))
    },
    formRules() {
      return {
        subsidyProjectName: [
          { required: true, message: this.pubT("ruleProjectNameRequired"), trigger: "blur" },
          { min: 1, max: 20, message: this.$t("policy.common.ruleLen120"), trigger: "blur" }
        ],
        subsidyType: [{ required: true, message: this.pubT("ruleSubsidyTypeRequired"), trigger: "change" }],
        recipientName: [
          { required: true, message: this.pubT("ruleRecipientNameRequired"), trigger: "blur" },
          { min: 1, max: 10, message: this.pubT("ruleRecipientNameRequired"), trigger: "blur" }
        ],
        idCard: [
          { required: true, message: this.pubT("ruleIdCardRequired"), trigger: "blur" },
          { validator: this.validateIdCard, trigger: "blur" }
        ],
        contactPhone: [
          { required: true, message: this.pubT("rulePhoneRequired"), trigger: "blur" },
          { validator: this.validatePhone, trigger: "blur" }
        ],
        bankAccount: [
          { required: true, message: this.pubT("ruleBankRequired"), trigger: "blur" },
          { validator: this.validateBankAccount, trigger: "blur" }
        ],
        subsidyAmount: [
          { required: true, message: this.pubT("ruleAmountRequired"), trigger: "blur" },
          { validator: this.validateAmount, trigger: "blur" }
        ],
        grantDate: [
          { required: true, message: this.pubT("ruleGrantDateRequired"), trigger: "change" },
          { validator: this.validateGrantDate, trigger: "change" }
        ]
      }
    },
    grantDatePickerOptions() {
      return {
        disabledDate: (time) => time.getTime() > Date.now()
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    typeLabel(val) {
      const item = this.subsidyTypeOptions.find((o) => o.value === val)
      return item ? item.label : ""
    },
    formatAmount(val) {
      if (val == null || val === "") {
        return this.$t("policy.status.dash")
      }
      return val + " " + this.pubT("yuan")
    },
    validateIdCard(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      if (!ID_CARD_REG.test(value)) {
        callback(new Error(this.pubT("ruleIdCardInvalid")))
      } else {
        callback()
      }
    },
    validatePhone(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      if (!PHONE_REG.test(value)) {
        callback(new Error(this.pubT("rulePhoneInvalid")))
      } else {
        callback()
      }
    },
    validateBankAccount(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      if (!BANK_REG.test(value)) {
        callback(new Error(this.pubT("ruleBankInvalid")))
      } else {
        callback()
      }
    },
    validateAmount(rule, value, callback) {
      if (value == null || value === "" || Number(value) <= 0) {
        callback(new Error(this.pubT("ruleAmountInvalid")))
      } else {
        callback()
      }
    },
    validateGrantDate(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      const today = new Date()
      today.setHours(23, 59, 59, 999)
      const picked = new Date(String(value).replace(/-/g, "/"))
      if (picked.getTime() > today.getTime()) {
        callback(new Error(this.pubT("ruleGrantDateFuture")))
      } else {
        callback()
      }
    },
    checkQueryDateRange() {
      const { startDate, endDate } = this.queryParams
      if (startDate && endDate && startDate > endDate) {
        this.$modal.msgError(this.pubT("ruleDateRangeInvalid"))
        return false
      }
      return true
    },
    getList() {
      if (!this.checkQueryDateRange()) {
        return
      }
      this.loading = true
      listSubsidyRecord(this.queryParams)
        .then((res) => {
          this.tableList = res.rows || []
          this.total = res.total != null ? res.total : 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams.recipientName = undefined
      this.queryParams.subsidyType = undefined
      this.queryParams.startDate = undefined
      this.queryParams.endDate = undefined
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
    },
    resetFormModel() {
      this.form = {
        id: undefined,
        subsidyProjectName: undefined,
        subsidyType: undefined,
        recipientName: undefined,
        idCard: undefined,
        contactPhone: undefined,
        bankAccount: undefined,
        subsidyAmount: undefined,
        grantDate: undefined,
        remark: undefined
      }
    },
    handleAdd() {
      this.formKey += 1
      this.resetFormModel()
      this.dialogEdit = false
      this.open = true
      this.$nextTick(() => this.resetForm("form"))
    },
    handleEdit(row) {
      getSubsidyRecord(row.id).then((res) => {
        const data = res.data || {}
        this.formKey += 1
        this.dialogEdit = true
        this.form = {
          id: data.id,
          subsidyProjectName: data.subsidyProjectName,
          subsidyType: data.subsidyType,
          recipientName: data.recipientName,
          idCard: data.idCard,
          contactPhone: data.contactPhone,
          bankAccount: data.bankAccount,
          subsidyAmount: data.subsidyAmount != null ? Number(data.subsidyAmount) : undefined,
          grantDate: data.grantDate,
          remark: data.remark
        }
        this.open = true
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      })
    },
    handleView(row) {
      getSubsidyRecord(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleDelete(row) {
      this.$modal
        .confirm(this.$t("policy.subsidyRecord.confirmDelete", { id: row.id }))
        .then(() => delSubsidyRecord(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.$t("policy.common.msgDelOk"))
          this.getList()
        })
        .catch(() => {})
    },
    handleDeleteBatch() {
      if (!this.ids.length) {
        return
      }
      this.$modal
        .confirm(this.pubT("confirmDeleteBatch"))
        .then(() => delSubsidyRecord(this.ids.join(",")))
        .then(() => {
          this.$modal.msgSuccess(this.$t("policy.common.msgDelOk"))
          this.getList()
        })
        .catch(() => {})
    },
    handleExport() {
      if (!this.checkQueryDateRange()) {
        return
      }
      this.download(
        "industryPolicy/subsidyRecord/export",
        { ...this.queryParams },
        `subsidy_record_${new Date().getTime()}.xlsx`
      )
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        const payload = {
          subsidyProjectName: this.form.subsidyProjectName,
          subsidyType: this.form.subsidyType,
          recipientName: this.form.recipientName,
          idCard: this.form.idCard,
          contactPhone: this.form.contactPhone,
          bankAccount: this.form.bankAccount,
          subsidyAmount: this.form.subsidyAmount,
          grantDate: this.form.grantDate,
          remark: this.form.remark || undefined
        }
        if (this.dialogEdit) {
          payload.id = this.form.id
          updateSubsidyRecord(payload).then(() => {
            this.$modal.msgSuccess(this.$t("policy.common.msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addSubsidyRecord(payload).then(() => {
            this.$modal.msgSuccess(this.$t("policy.common.msgAddOk"))
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.open = false
      this.resetFormModel()
    }
  }
}
</script>
