<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item prop="distributorCode">
          <template slot="label">{{ tmT("queryDistributorCode") }}</template>
          <el-input
            v-model="queryParams.distributorCode"
            :placeholder="tmT('queryDistributorCodePh')"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="distributorName">
          <template slot="label">{{ tmT("queryDistributorName") }}</template>
          <el-input
            v-model="queryParams.distributorName"
            :placeholder="tmT('queryDistributorNamePh')"
            clearable
            style="width: 220px"
            @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:distributor: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('colDistributorCode')" prop="distributorCode" align="center" width="100" />
        <el-table-column :label="tmT('colDistributorName')" prop="distributorName" align="center" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column :label="tmT('colDistributorType')" align="center" width="90">
          <template slot-scope="scope">
            <span>{{ distributorTypeLabel(scope.row.distributorType, scope.row.distributorTypeName) }}</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('colSalesDestination')" align="center" width="90">
          <template slot-scope="scope">
            <span>{{ salesDestinationLabel(scope.row.salesDestination, scope.row.salesDestinationName) }}</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:distributor:query']" type="text" size="mini" @click="handleView(scope.row)">{{ tmCommon("view") }}</el-button>
            <el-button v-hasPermi="['tradeMarket:distributor:edit']" type="text" size="mini" @click="handleEdit(scope.row)">{{ tmCommon("edit") }}</el-button>
            <el-button
              v-hasPermi="['tradeMarket:distributor:assignAccount']"
              v-if="canAssignAccount(scope.row)"
              type="text"
              size="mini"
              @click="handleAssignAccount(scope.row)"
            >{{ tmCommon("assignAccount") }}</el-button>
            <el-button v-hasPermi="['tradeMarket:distributor: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="720px" append-to-body @close="cancel">
      <el-form :key="formKey" ref="form" :model="form" label-width="140px">
        <el-form-item prop="distributorCode">
          <template slot="label">{{ tmT("formDistributorCode") }}</template>
          <el-input v-model="form.distributorCode" :placeholder="tmT('phDistributorCodeAuto')" :disabled="true" />
        </el-form-item>
        <el-form-item prop="distributorName" :rules="formRules.distributorName">
              <template slot="label">{{ tmT("formDistributorName") }}</template>
              <el-input v-model="form.distributorName" :placeholder="tmT('phDistributorName')" maxlength="20" show-word-limit />
            </el-form-item>
            <el-form-item prop="distributorType" :rules="formRules.distributorType">
              <template slot="label">{{ tmT("formDistributorType") }}</template>
              <el-select
                v-model="form.distributorType"
                :placeholder="tmCommon('pleaseSelect')"
                style="width: 100%"
                @change="onDistributorTypeChange"
              >
                <el-option v-for="item in distributorTypeOptions" :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 prop="salesDestination" :rules="formRules.salesDestination">
          <template slot="label">{{ tmT("formSalesDestination") }}</template>
          <el-select v-model="form.salesDestination" :placeholder="tmCommon('pleaseSelect')" style="width: 100%">
            <el-option v-for="item in salesDestinationOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <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('formDistributorCode')">
          <span>{{ viewRow.distributorCode || dash }}</span>
        </el-form-item>
        <el-form-item :label="tmT('formDistributorName')">
          <span>{{ viewRow.distributorName || dash }}</span>
        </el-form-item>
        <el-form-item :label="tmT('formDistributorType')">
          <span>{{ distributorTypeLabel(viewRow.distributorType, viewRow.distributorTypeName) }}</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('formSalesDestination')">
          <span>{{ salesDestinationLabel(viewRow.salesDestination, viewRow.salesDestinationName) }}</span>
        </el-form-item>
        <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:distributor:assignAccount']"
          v-if="canAssignAccount(viewRow)"
          type="primary"
          plain
          @click="handleAssignAccount(viewRow)"
        >{{ tmCommon("assignAccount") }}</el-button>
        <el-button v-hasPermi="['tradeMarket:distributor:edit']" type="primary" plain @click="openEditFromView">{{ tmCommon("edit") }}</el-button>
        <el-button v-hasPermi="['tradeMarket:distributor: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 {
  listDistributor,
  getDistributor,
  addDistributor,
  updateDistributor,
  delDistributor,
  assignAccountDistributor
} from "@/api/tradeMarket/distributor"

const DISTRIBUTOR_TYPE_INDIVIDUAL = 1
const DISTRIBUTOR_TYPE_ENTERPRISE = 2
const SALES_DEST_CITY = 1
const SALES_DEST_PROVINCE = 2
const SALES_DEST_OUTER = 3

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}$/

function createEmptyForm() {
  return {
    id: undefined,
    distributorCode: undefined,
    distributorName: undefined,
    distributorType: DISTRIBUTOR_TYPE_INDIVIDUAL,
    identityNo: undefined,
    contactPhone: undefined,
    businessLocation: undefined,
    salesDestination: undefined,
    remark: undefined
  }
}

export default {
  name: "TradeMarketDistributor",
  mixins: [tradeMarketLocaleMixin],
  data() {
    return {
      tmNs: "distributor",
      loading: false,
      open: false,
      viewOpen: false,
      viewRow: {},
      dialogEdit: false,
      formKey: 0,
      total: 0,
      tableList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        distributorCode: undefined,
        distributorName: undefined
      },
      form: createEmptyForm()
    }
  },
  computed: {
    dash() {
      return this.$t("tradeMarket.status.dash")
    },
    dialogTitle() {
      return this.dialogEdit ? this.tmT("dialogEdit") : this.tmT("dialogAdd")
    },
    distributorTypeOptions() {
      return [
        { value: DISTRIBUTOR_TYPE_INDIVIDUAL, label: this.tmT("distributorType1") },
        { value: DISTRIBUTOR_TYPE_ENTERPRISE, label: this.tmT("distributorType2") }
      ]
    },
    salesDestinationOptions() {
      return [
        { value: SALES_DEST_CITY, label: this.tmT("salesDestination1") },
        { value: SALES_DEST_PROVINCE, label: this.tmT("salesDestination2") },
        { value: SALES_DEST_OUTER, label: this.tmT("salesDestination3") }
      ]
    },
    identityFieldLabel() {
      return this.form.distributorType === DISTRIBUTOR_TYPE_ENTERPRISE
        ? this.tmT("formIdentityNoEnterprise")
        : this.tmT("formIdentityNo")
    },
    identityPlaceholder() {
      return this.form.distributorType === DISTRIBUTOR_TYPE_ENTERPRISE
        ? this.tmT("phIdentityNoEnterprise")
        : this.tmT("phIdentityNo")
    },
    formRules() {
      return {
        distributorName: [
          { required: true, message: this.tmT("ruleDistributorNameRequired"), trigger: "blur" },
          { validator: this.validateDistributorName, trigger: "blur" }
        ],
        distributorType: [{ required: true, message: this.tmT("ruleDistributorTypeRequired"), 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" }],
        salesDestination: [{ required: true, message: this.tmT("ruleSalesDestinationRequired"), trigger: "change" }],
        remark: [{ validator: this.validateRemark, trigger: "blur" }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    distributorTypeLabel(val, name) {
      if (name) {
        return name
      }
      const item = this.distributorTypeOptions.find((o) => o.value === val)
      return item ? item.label : this.dash
    },
    salesDestinationLabel(val, name) {
      if (name) {
        return name
      }
      const item = this.salesDestinationOptions.find((o) => o.value === val)
      return item ? item.label : this.dash
    },
    identityLabelForRow(row) {
      return row && row.distributorType === DISTRIBUTOR_TYPE_ENTERPRISE
        ? this.tmT("formIdentityNoEnterprise")
        : this.tmT("formIdentityNo")
    },
    canAssignAccount(row) {
      return row && Number(row.accountAssigned) === 0
    },
    validateDistributorName(rule, value, callback) {
      const text = value != null ? String(value).trim() : ""
      if (!text) {
        callback(new Error(this.tmT("ruleDistributorNameRequired")))
        return
      }
      if (text.length > 20) {
        callback(new Error(this.tmT("ruleDistributorNameLen")))
        return
      }
      callback()
    },
    validateIdentityNo(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      const v = String(value).trim().toUpperCase()
      if (this.form.distributorType === DISTRIBUTOR_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()
    },
    validateRemark(rule, value, callback) {
      if (value != null && String(value).length > 500) {
        callback(new Error(this.tmT("ruleRemarkLen")))
        return
      }
      callback()
    },
    onDistributorTypeChange() {
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.validateField("identityNo", () => {})
        }
      })
    },
    resetFormModel() {
      this.form = createEmptyForm()
    },
    fillFormFromData(data) {
      this.form = Object.assign(createEmptyForm(), {
        id: data.id,
        distributorCode: data.distributorCode,
        distributorName: data.distributorName,
        distributorType: data.distributorType,
        identityNo: data.identityNo,
        contactPhone: data.contactPhone,
        businessLocation: data.businessLocation,
        salesDestination: data.salesDestination,
        remark: data.remark
      })
    },
    buildPayload() {
      return {
        distributorName: this.form.distributorName != null ? String(this.form.distributorName).trim() : undefined,
        distributorType: this.form.distributorType,
        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,
        salesDestination: this.form.salesDestination,
        remark: this.form.remark
      }
    },
    getList() {
      this.loading = true
      listDistributor(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.distributorCode = undefined
      this.queryParams.distributorName = 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) {
      getDistributor(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) {
      getDistributor(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleDelete(row) {
      this.$modal
        .confirm(
          this.tmT("confirmDelete", {
            code: row.distributorCode || row.id,
            name: row.distributorName || ""
          })
        )
        .then(() => delDistributor(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.distributorName || row.distributorCode || row.id
          })
        )
        .then(() => assignAccountDistributor(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.tmCommon("msgAssignOk"))
          if (this.viewOpen && this.viewRow && this.viewRow.id === row.id) {
            getDistributor(row.id).then((res) => {
              this.viewRow = res.data || {}
            })
          }
          this.getList()
        })
        .catch(() => {})
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        const payload = this.buildPayload()
        if (this.dialogEdit) {
          payload.id = this.form.id
          updateDistributor(payload).then(() => {
            this.$modal.msgSuccess(this.tmCommon("msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addDistributor(payload).then(() => {
            this.$modal.msgSuccess(this.tmCommon("msgAddOk"))
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.open = false
      this.resetFormModel()
    }
  }
}
</script>
