<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item prop="supplierCode">
          <template slot="label">{{ tmT("querySupplierCode") }}</template>
          <el-input
            v-model="queryParams.supplierCode"
            :placeholder="tmT('querySupplierCodePh')"
            clearable
            style="width: 180px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="supplierName">
          <template slot="label">{{ tmT("querySupplierName") }}</template>
          <el-input
            v-model="queryParams.supplierName"
            :placeholder="tmT('querySupplierNamePh')"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ tmCommon("search") }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ tmCommon("reset") }}</el-button>
          <el-button
            v-hasPermi="['tradeMarket:supplier:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ tmCommon("add") }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <br />

    <el-card shadow="never">
      <el-table v-loading="loading" :data="tableList" border>
        <el-table-column :label="tmT('colSupplierCode')" prop="supplierCode" align="center" width="100" />
        <el-table-column :label="tmT('colSupplierName')" prop="supplierName" align="center" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column :label="tmT('colSupplierType')" align="center" width="90">
          <template slot-scope="scope">
            <span>{{ supplierTypeLabel(scope.row.supplierType, scope.row.supplierTypeName) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="tmT('colIdentityNo')" prop="identityNo" align="center" min-width="160" :show-overflow-tooltip="true" />
        <el-table-column :label="tmT('colContactPhone')" prop="contactPhone" align="center" width="120" />
        <el-table-column :label="tmT('colBusinessLocation')" prop="businessLocation" align="center" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column :label="tmT('colVehiclePlates')" align="center" min-width="120" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ formatVehiclePlatesDisplay(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="tmT('colFeeMethod')" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ feeMethodLabel(scope.row.feeMethod, scope.row.feeMethodName) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="tmT('colAccount')" align="center" min-width="120">
          <template slot-scope="scope">
            <span v-if="Number(scope.row.accountAssigned) === 1">
              {{ $t('tradeMarket.status.yes') }}
              <template v-if="scope.row.assignedLoginName">（{{ scope.row.assignedLoginName }}）</template>
            </span>
            <span v-else>{{ $t('tradeMarket.status.no') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="tmCommon('colOp')" align="center" class-name="small-padding fixed-width" width="260" fixed="right">
          <template slot-scope="scope">
            <el-button v-hasPermi="['tradeMarket:supplier:query']" type="text" size="mini" @click="handleView(scope.row)">{{ tmCommon("view") }}</el-button>
            <el-button v-hasPermi="['tradeMarket:supplier:edit']" type="text" size="mini" @click="handleEdit(scope.row)">{{ tmCommon("edit") }}</el-button>
            <el-button
              v-hasPermi="['tradeMarket:supplier:assignAccount']"
              v-if="canAssignAccount(scope.row)"
              type="text"
              size="mini"
              @click="handleAssignAccount(scope.row)"
            >{{ tmCommon("assignAccount") }}</el-button>
            <el-button v-hasPermi="['tradeMarket:supplier:remove']" type="text" size="mini" @click="handleDelete(scope.row)">{{ tmCommon("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="550px" append-to-body @close="cancel">
      <el-form :key="formKey" ref="form" :model="form" label-width="140px">
        <el-form-item prop="supplierCode">
          <template slot="label">{{ tmT("formSupplierCode") }}</template>
          <el-input
            v-model="form.supplierCode"
            :placeholder="tmT('phSupplierCodeAuto')"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item prop="supplierName" :rules="formRules.supplierName">
              <template slot="label">{{ tmT("formSupplierName") }}</template>
              <el-input v-model="form.supplierName" :placeholder="tmT('phSupplierName')" maxlength="20" show-word-limit />
            </el-form-item>
             <el-form-item prop="supplierType" :rules="formRules.supplierType">
              <template slot="label">{{ tmT("formSupplierType") }}</template>
              <el-select
                v-model="form.supplierType"
                :placeholder="tmCommon('pleaseSelect')"
                style="width: 100%"
                @change="onSupplierTypeChange"
              >
                <el-option v-for="item in supplierTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
        <el-form-item prop="identityNo" :rules="formRules.identityNo">
          <template slot="label">{{ identityFieldLabel }}</template>
          <el-input
            v-model="form.identityNo"
            :placeholder="identityPlaceholder"
            maxlength="18"
            show-word-limit
          />
        </el-form-item>
        <el-form-item prop="contactPhone" :rules="formRules.contactPhone">
          <template slot="label">{{ tmT("formContactPhone") }}</template>
          <el-input v-model="form.contactPhone" :placeholder="tmT('phContactPhone')" maxlength="11" />
        </el-form-item>
        <el-form-item prop="businessLocation" :rules="formRules.businessLocation">
          <template slot="label">{{ tmT("formBusinessLocation") }}</template>
          <el-input v-model="form.businessLocation" type="textarea" :rows="2" :placeholder="tmT('phBusinessLocation')" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item>
          <template slot="label">{{ tmT("formVehiclePlates") }}</template>
          <div v-for="(plate, index) in vehiclePlateListSafe" :key="'plate-' + index" class="supplier-plate-row">
            <el-input
              v-model="form.vehiclePlateList[index]"
              :placeholder="tmT('phVehiclePlate')"
              maxlength="16"
              style="width: 280px"
            />
            <el-button
              v-if="vehiclePlateListSafe.length > 1"
              type="text"
              icon="el-icon-remove-outline"
              @click="removeVehiclePlate(index)"
            />
          </div>
          <el-button
            v-if="vehiclePlateListSafe.length < maxVehiclePlates"
            type="text"
            icon="el-icon-circle-plus-outline"
            @click="addVehiclePlate"
          >{{ tmCommon("addRow") }}</el-button>
        </el-form-item>
        <el-form-item prop="feeMethod" :rules="formRules.feeMethod">
          <template slot="label">{{ tmT("formFeeMethod") }}</template>
          <el-select
            v-model="form.feeMethod"
            :placeholder="tmCommon('pleaseSelect')"
            style="width: 100%"
            @change="onFeeMethodChange"
          >
            <el-option v-for="item in feeMethodOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="showFeeStandard" prop="feeStandard" :rules="formRules.feeStandard">
          <template slot="label">{{ tmT("formFeeStandard") }}</template>
          <el-input-number
            v-model="form.feeStandard"
            :min="0.01"
            :max="99999999"
            :precision="2"
            :step="1"
            controls-position="right"
            style="width: 200px"
          />
          <span class="supplier-unit">{{ tmT("unitYuanPerHead") }}</span>
        </el-form-item>
        <template v-if="showFeeRates">
          <el-form-item prop="transactionFeeRate" :rules="formRules.transactionFeeRate">
            <template slot="label">{{ tmT("formTransactionFeeRate") }}</template>
            <el-input-number
              v-model="form.transactionFeeRate"
              :min="0"
              :max="100"
              :precision="2"
              :step="0.1"
              controls-position="right"
              style="width: 200px"
            />
            <span class="supplier-unit">{{ tmT("unitPercent") }}</span>
          </el-form-item>
          <el-form-item prop="managementFeeRate" :rules="formRules.managementFeeRate">
            <template slot="label">{{ tmT("formManagementFeeRate") }}</template>
            <el-input-number
              v-model="form.managementFeeRate"
              :min="0"
              :max="100"
              :precision="2"
              :step="0.1"
              controls-position="right"
              style="width: 200px"
            />
            <span class="supplier-unit">{{ tmT("unitPercent") }}</span>
          </el-form-item>
        </template>
        <el-form-item prop="remark" :rules="formRules.remark">
          <template slot="label">{{ tmT("formRemark") }}</template>
          <el-input v-model="form.remark" type="textarea" :rows="2" :placeholder="tmT('phRemark')" maxlength="500" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ tmCommon("ok") }}</el-button>
        <el-button @click="cancel">{{ tmCommon("cancel") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="tmCommon('viewTitle')" :visible.sync="viewOpen" width="720px" append-to-body>
      <el-form label-width="140px" size="small">
        <el-form-item :label="tmT('formSupplierCode')">
          <span>{{ viewRow.supplierCode || dash }}</span>
        </el-form-item>
        <el-form-item :label="tmT('formSupplierName')">
          <span>{{ viewRow.supplierName || dash }}</span>
        </el-form-item>
        <el-form-item :label="tmT('formSupplierType')">
          <span>{{ supplierTypeLabel(viewRow.supplierType, viewRow.supplierTypeName) }}</span>
        </el-form-item>
        <el-form-item :label="identityLabelForRow(viewRow)">
          <span>{{ viewRow.identityNo || dash }}</span>
        </el-form-item>
        <el-form-item :label="tmT('formContactPhone')">
          <span>{{ viewRow.contactPhone || dash }}</span>
        </el-form-item>
        <el-form-item :label="tmT('formBusinessLocation')">
          <span>{{ viewRow.businessLocation || dash }}</span>
        </el-form-item>
        <el-form-item :label="tmT('formVehiclePlates')">
          <span>{{ formatVehiclePlatesDisplay(viewRow) }}</span>
        </el-form-item>
        <el-form-item :label="tmT('formFeeMethod')">
          <span>{{ feeMethodLabel(viewRow.feeMethod, viewRow.feeMethodName) }}</span>
        </el-form-item>
        <el-form-item v-if="viewRow.feeMethod === FEE_METHOD_HEAD" :label="tmT('viewFeeStandard')">
          <span>{{ viewRow.feeStandard != null ? viewRow.feeStandard + " " + tmT("unitYuanPerHead") : dash }}</span>
        </el-form-item>
        <template v-if="viewRow.feeMethod === FEE_METHOD_AMOUNT">
          <el-form-item :label="tmT('viewTransactionFee')">
            <span>{{ viewRow.transactionFeeRate != null ? viewRow.transactionFeeRate + tmT("unitPercent") : dash }}</span>
          </el-form-item>
          <el-form-item :label="tmT('viewManagementFee')">
            <span>{{ viewRow.managementFeeRate != null ? viewRow.managementFeeRate + tmT("unitPercent") : dash }}</span>
          </el-form-item>
        </template>
        <el-form-item :label="tmT('formRemark')">
          <span>{{ viewRow.remark || dash }}</span>
        </el-form-item>
        <el-form-item :label="tmT('colAccount')">
          <span>{{ Number(viewRow.accountAssigned) === 1 ? $t('tradeMarket.status.yes') : $t('tradeMarket.status.no') }}</span>
        </el-form-item>
        <el-form-item v-if="viewRow.assignedLoginName" :label="tmT('viewAssignedLogin')">
          <span>{{ viewRow.assignedLoginName }}</span>
        </el-form-item>
        <el-form-item :label="tmT('viewCreateBy')">
          <span>{{ viewRow.createBy || dash }}</span>
        </el-form-item>
        <el-form-item :label="tmT('viewUpdateBy')">
          <span>{{ viewRow.updateBy || dash }}</span>
        </el-form-item>
        <el-form-item :label="tmT('viewUpdateTime')">
          <span>{{ viewRow.updateTime ? parseTime(viewRow.updateTime) : dash }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-hasPermi="['tradeMarket:supplier:assignAccount']"
          v-if="canAssignAccount(viewRow)"
          type="primary"
          plain
          @click="handleAssignAccount(viewRow)"
        >{{ tmCommon("assignAccount") }}</el-button>
        <el-button v-hasPermi="['tradeMarket:supplier:edit']" type="primary" plain @click="openEditFromView">{{ tmCommon("edit") }}</el-button>
        <el-button v-hasPermi="['tradeMarket:supplier:remove']" type="danger" plain @click="handleDelete(viewRow)">{{ tmCommon("delete") }}</el-button>
        <el-button @click="viewOpen = false">{{ tmCommon("close") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import tradeMarketLocaleMixin from "@/mixins/tradeMarketLocaleMixin"
import { listSupplier, getSupplier, addSupplier, updateSupplier, delSupplier, assignAccountSupplier } from "@/api/tradeMarket/supplier"

const SUPPLIER_TYPE_INDIVIDUAL = 1
const SUPPLIER_TYPE_ENTERPRISE = 2
const FEE_METHOD_HOUSEHOLD = 1
const FEE_METHOD_HEAD = 2
const FEE_METHOD_AMOUNT = 3
const MAX_VEHICLE_PLATES = 10

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 USCC_REG = /^[0-9A-Z]{18}$/
const PHONE_REG = /^1[3-9]\d{9}$/
const PLATE_REG = /^[\u4e00-\u9fa5][A-Z][A-Z0-9]{5,6}$/

function createEmptyForm() {
  return {
    id: undefined,
    supplierCode: undefined,
    supplierName: undefined,
    supplierType: SUPPLIER_TYPE_INDIVIDUAL,
    identityNo: undefined,
    contactPhone: undefined,
    businessLocation: undefined,
    vehiclePlateList: [""],
    feeMethod: undefined,
    feeStandard: undefined,
    transactionFeeRate: undefined,
    managementFeeRate: undefined,
    remark: undefined
  }
}

export default {
  name: "TradeMarketSupplier",
  mixins: [tradeMarketLocaleMixin],
  data() {
    return {
      tmNs: "supplier",
      FEE_METHOD_HEAD,
      FEE_METHOD_AMOUNT,
      loading: false,
      open: false,
      viewOpen: false,
      viewRow: {},
      dialogEdit: false,
      formKey: 0,
      total: 0,
      tableList: [],
      maxVehiclePlates: MAX_VEHICLE_PLATES,
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        supplierCode: undefined,
        supplierName: undefined
      },
      form: createEmptyForm()
    }
  },
  computed: {
    vehiclePlateListSafe() {
      return this.form.vehiclePlateList || [""]
    },
    dash() {
      return this.$t("tradeMarket.status.dash")
    },
    dialogTitle() {
      return this.dialogEdit ? this.tmT("dialogEdit") : this.tmT("dialogAdd")
    },
    supplierTypeOptions() {
      return [
        { value: SUPPLIER_TYPE_INDIVIDUAL, label: this.tmT("supplierType1") },
        { value: SUPPLIER_TYPE_ENTERPRISE, label: this.tmT("supplierType2") }
      ]
    },
    feeMethodOptions() {
      return [
        { value: FEE_METHOD_HOUSEHOLD, label: this.tmT("feeMethod1") },
        { value: FEE_METHOD_HEAD, label: this.tmT("feeMethod2") },
        { value: FEE_METHOD_AMOUNT, label: this.tmT("feeMethod3") }
      ]
    },
    identityFieldLabel() {
      return this.form.supplierType === SUPPLIER_TYPE_ENTERPRISE
        ? this.tmT("formIdentityNoEnterprise")
        : this.tmT("formIdentityNo")
    },
    identityPlaceholder() {
      return this.form.supplierType === SUPPLIER_TYPE_ENTERPRISE
        ? this.tmT("phIdentityNoEnterprise")
        : this.tmT("phIdentityNo")
    },
    showFeeStandard() {
      return this.form.feeMethod === FEE_METHOD_HEAD
    },
    showFeeRates() {
      return this.form.feeMethod === FEE_METHOD_AMOUNT
    },
    formRules() {
      return {
        supplierName: [
          { required: true, message: this.tmT("ruleSupplierNameRequired"), trigger: "blur" },
          { validator: this.validateSupplierName, trigger: "blur" }
        ],
        supplierType: [{ required: true, message: this.tmT("ruleSupplierTypeRequired"), trigger: "change" }],
        identityNo: [
          { required: true, message: this.tmT("ruleIdentityNoRequired"), trigger: "blur" },
          { validator: this.validateIdentityNo, trigger: "blur" }
        ],
        contactPhone: [
          { required: true, message: this.tmT("rulePhoneRequired"), trigger: "blur" },
          { validator: this.validatePhone, trigger: "blur" }
        ],
        businessLocation: [{ validator: this.validateBusinessLocation, trigger: "blur" }],
        feeMethod: [{ required: true, message: this.tmT("ruleFeeMethodRequired"), trigger: "change" }],
        feeStandard: [{ validator: this.validateFeeStandard, trigger: "change" }],
        transactionFeeRate: [{ validator: this.validateTransactionFeeRate, trigger: "change" }],
        managementFeeRate: [{ validator: this.validateManagementFeeRate, trigger: "change" }],
        remark: [{ validator: this.validateRemark, trigger: "blur" }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    supplierTypeLabel(val, name) {
      if (name) {
        return name
      }
      const item = this.supplierTypeOptions.find((o) => o.value === val)
      return item ? item.label : this.dash
    },
    feeMethodLabel(val, name) {
      if (name) {
        return name
      }
      const item = this.feeMethodOptions.find((o) => o.value === val)
      return item ? item.label : this.dash
    },
    identityLabelForRow(row) {
      return row && row.supplierType === SUPPLIER_TYPE_ENTERPRISE
        ? this.tmT("formIdentityNoEnterprise")
        : this.tmT("formIdentityNo")
    },
    canAssignAccount(row) {
      return row && Number(row.accountAssigned) === 0
    },
    normalizePlates(raw) {
      if (!raw) {
        return []
      }
      if (Array.isArray(raw)) {
        return raw.filter((p) => p != null && String(p).trim())
      }
      if (typeof raw === "string") {
        try {
          const parsed = JSON.parse(raw)
          if (Array.isArray(parsed)) {
            return parsed.filter((p) => p != null && String(p).trim())
          }
        } catch (e) {
          return raw
            .split(/[,，、]/)
            .map((s) => s.trim())
            .filter(Boolean)
        }
      }
      return []
    },
    formatVehiclePlatesDisplay(row) {
      const plates = this.normalizePlates(row.vehiclePlates)
      return plates.length ? plates.join("、") : this.dash
    },
    validateSupplierName(rule, value, callback) {
      const text = value != null ? String(value).trim() : ""
      if (!text) {
        callback(new Error(this.tmT("ruleSupplierNameRequired")))
        return
      }
      if (text.length > 20) {
        callback(new Error(this.tmT("ruleSupplierNameLen")))
        return
      }
      callback()
    },
    validateIdentityNo(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      const v = String(value).trim().toUpperCase()
      if (this.form.supplierType === SUPPLIER_TYPE_ENTERPRISE) {
        if (!USCC_REG.test(v)) {
          callback(new Error(this.tmT("ruleUsccInvalid")))
          return
        }
      } else if (!ID_CARD_REG.test(v)) {
        callback(new Error(this.tmT("ruleIdCardInvalid")))
        return
      }
      callback()
    },
    validatePhone(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      if (!PHONE_REG.test(String(value).trim())) {
        callback(new Error(this.tmT("rulePhoneInvalid")))
        return
      }
      callback()
    },
    validateBusinessLocation(rule, value, callback) {
      if (value != null && String(value).length > 50) {
        callback(new Error(this.tmT("ruleLocationLen")))
        return
      }
      callback()
    },
    validateFeeStandard(rule, value, callback) {
      if (this.form.feeMethod !== FEE_METHOD_HEAD) {
        callback()
        return
      }
      if (value == null || Number(value) <= 0) {
        callback(new Error(this.tmT("ruleFeeStandardRequired")))
        return
      }
      callback()
    },
    validateTransactionFeeRate(rule, value, callback) {
      if (this.form.feeMethod !== FEE_METHOD_AMOUNT) {
        callback()
        return
      }
      if (value == null || value === "") {
        callback(new Error(this.tmT("ruleTransactionFeeRequired")))
        return
      }
      const n = Number(value)
      if (n < 0 || n > 100) {
        callback(new Error(this.tmT("ruleFeeRateRange")))
        return
      }
      callback()
    },
    validateManagementFeeRate(rule, value, callback) {
      if (this.form.feeMethod !== FEE_METHOD_AMOUNT) {
        callback()
        return
      }
      if (value == null || value === "") {
        callback(new Error(this.tmT("ruleManagementFeeRequired")))
        return
      }
      const n = Number(value)
      if (n < 0 || n > 100) {
        callback(new Error(this.tmT("ruleFeeRateRange")))
        return
      }
      callback()
    },
    validateRemark(rule, value, callback) {
      if (value != null && String(value).length > 500) {
        callback(new Error(this.tmT("ruleRemarkLen")))
        return
      }
      callback()
    },
    validateVehiclePlates() {
      this.ensureVehiclePlateList()
      const list = this.form.vehiclePlateList
        .map((p) => (p != null ? String(p).trim().toUpperCase() : ""))
        .filter(Boolean)
      if (list.length > MAX_VEHICLE_PLATES) {
        this.$modal.msgError(this.tmT("rulePlateMax"))
        return false
      }
      for (let i = 0; i < list.length; i++) {
        if (!PLATE_REG.test(list[i])) {
          this.$modal.msgError(this.tmT("rulePlateInvalid"))
          return false
        }
      }
      return true
    },
    onSupplierTypeChange() {
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.validateField("identityNo", () => {})
        }
      })
    },
    onFeeMethodChange() {
      if (this.form.feeMethod === FEE_METHOD_HOUSEHOLD) {
        this.form.feeStandard = undefined
        this.form.transactionFeeRate = undefined
        this.form.managementFeeRate = undefined
      } else if (this.form.feeMethod === FEE_METHOD_HEAD) {
        this.form.transactionFeeRate = undefined
        this.form.managementFeeRate = undefined
      } else if (this.form.feeMethod === FEE_METHOD_AMOUNT) {
        this.form.feeStandard = undefined
      }
    },
    addVehiclePlate() {
      this.ensureVehiclePlateList()
      if (this.form.vehiclePlateList.length >= MAX_VEHICLE_PLATES) {
        this.$modal.msgError(this.tmT("rulePlateMax"))
        return
      }
      this.form.vehiclePlateList.push("")
    },
    removeVehiclePlate(index) {
      this.ensureVehiclePlateList()
      this.form.vehiclePlateList.splice(index, 1)
      if (!this.form.vehiclePlateList.length) {
        this.form.vehiclePlateList.push("")
      }
    },
    resetFormModel() {
      this.form = createEmptyForm()
    },
    ensureVehiclePlateList() {
      if (!Array.isArray(this.form.vehiclePlateList)) {
        this.$set(this.form, "vehiclePlateList", [""])
      }
    },
    fillFormFromData(data) {
      const plates = this.normalizePlates(data.vehiclePlates)
      this.form = Object.assign(createEmptyForm(), {
        id: data.id,
        supplierCode: data.supplierCode,
        supplierName: data.supplierName,
        supplierType: data.supplierType,
        identityNo: data.identityNo,
        contactPhone: data.contactPhone,
        businessLocation: data.businessLocation,
        vehiclePlateList: plates.length ? plates : [""],
        feeMethod: data.feeMethod,
        feeStandard: data.feeStandard,
        transactionFeeRate: data.transactionFeeRate,
        managementFeeRate: data.managementFeeRate,
        remark: data.remark
      })
    },
    buildPayload() {
      this.ensureVehiclePlateList()
      const plates = this.form.vehiclePlateList
        .map((p) => (p != null ? String(p).trim().toUpperCase() : ""))
        .filter(Boolean)
      const payload = {
        supplierName: this.form.supplierName != null ? String(this.form.supplierName).trim() : undefined,
        supplierType: this.form.supplierType,
        identityNo: this.form.identityNo != null ? String(this.form.identityNo).trim().toUpperCase() : undefined,
        contactPhone: this.form.contactPhone != null ? String(this.form.contactPhone).trim() : undefined,
        businessLocation: this.form.businessLocation,
        vehiclePlates: plates.length ? plates : null,
        feeMethod: this.form.feeMethod,
        remark: this.form.remark
      }
      if (this.form.feeMethod === FEE_METHOD_HEAD) {
        payload.feeStandard = this.form.feeStandard
        payload.transactionFeeRate = null
        payload.managementFeeRate = null
      } else if (this.form.feeMethod === FEE_METHOD_AMOUNT) {
        payload.feeStandard = null
        payload.transactionFeeRate = this.form.transactionFeeRate
        payload.managementFeeRate = this.form.managementFeeRate
      } else {
        payload.feeStandard = null
        payload.transactionFeeRate = null
        payload.managementFeeRate = null
      }
      return payload
    },
    getList() {
      this.loading = true
      listSupplier(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.supplierCode = undefined
      this.queryParams.supplierName = undefined
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleAdd() {
      this.formKey += 1
      this.resetFormModel()
      this.dialogEdit = false
      this.open = true
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    handleEdit(row) {
      getSupplier(row.id).then((res) => {
        const data = res.data || {}
        this.formKey += 1
        this.dialogEdit = true
        this.fillFormFromData(data)
        this.open = true
        this.viewOpen = false
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      })
    },
    openEditFromView() {
      this.handleEdit(this.viewRow)
    },
    handleView(row) {
      getSupplier(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleDelete(row) {
      this.$modal
        .confirm(
          this.tmT("confirmDelete", {
            code: row.supplierCode || row.id,
            name: row.supplierName || ""
          })
        )
        .then(() => delSupplier(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.tmCommon("msgDelOk"))
          this.viewOpen = false
          this.getList()
        })
        .catch(() => {})
    },
    handleAssignAccount(row) {
      this.$modal
        .confirm(
          this.tmT("confirmAssign", {
            name: row.supplierName || row.supplierCode || row.id
          })
        )
        .then(() => assignAccountSupplier(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.tmCommon("msgAssignOk"))
          if (this.viewOpen && this.viewRow && this.viewRow.id === row.id) {
            getSupplier(row.id).then((res) => {
              this.viewRow = res.data || {}
            })
          }
          this.getList()
        })
        .catch(() => {})
    },
    submitForm() {
      if (!this.validateVehiclePlates()) {
        return
      }
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        const payload = this.buildPayload()
        if (this.dialogEdit) {
          payload.id = this.form.id
          updateSupplier(payload).then(() => {
            this.$modal.msgSuccess(this.tmCommon("msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addSupplier(payload).then((res) => {
            this.$modal.msgSuccess(this.tmCommon("msgAddOk"))
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.open = false
      this.resetFormModel()
    }
  }
}
</script>

<style scoped>
.supplier-plate-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.supplier-plate-row .el-button {
  margin-left: 8px;
}
.supplier-unit {
  margin-left: 8px;
  color: #606266;
}
</style>
