<template>
  <basic-container class="etc-record-page">
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model:page="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template #menu-left>
        <el-button
          type="primary"
          icon="el-icon-upload"
          plain
          v-if="hasPermission('etc_record_import')"
          @click="handleImport"
          >批量导入
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          plain
          v-if="hasPermission('etc_record_export')"
          @click="handleExport"
          >批量导出
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          plain
          v-if="hasPermission('etc_record_template')"
          @click="handleTemplate"
          >下载模板
        </el-button>
        <el-button
          type="danger"
          icon="el-icon-delete"
          plain
          v-if="hasPermission('etc_record_delete')"
          @click="handleDelete"
          >批量删除
        </el-button>
      </template>
      <template #vehicleNo="{ row, index }">
        <el-button type="primary" link @click="$refs.crud.rowView(row, index)">
          {{ row.vehicleNo }}
        </el-button>
      </template>
      <template #vehicleNoForm>
        <el-autocomplete
          v-model="form.vehicleNo"
          :fetch-suggestions="fetchVehicleOptions"
          :disabled="boxType === 'view'"
          clearable
          placeholder="输入车牌号模糊查询选择"
          value-key="value"
          class="etc-record-page__input"
        />
      </template>
      <template #transactionAmountForm>
        <el-input
          v-model="form.transactionAmount"
          :disabled="boxType === 'view'"
          inputmode="decimal"
          placeholder="请输入"
          @input="value => normalizeDecimalInput('transactionAmount', value)"
        >
          <template #suffix>元</template>
        </el-input>
      </template>
      <template #attachments="{ row }">
        <span>{{ formatAttachments(row.attachments) }}</span>
      </template>
      <template #attachmentsForm>
        <vehicle-attachment-upload v-model="form.attachments" :readonly="boxType === 'view'" />
      </template>
      <template #attachments-form>
        <vehicle-attachment-upload v-model="form.attachments" :readonly="boxType === 'view'" />
      </template>
    </avue-crud>
    <el-dialog title="ETC记录数据导入" append-to-body v-model="excelBox" width="555px">
      <avue-form :option="excelOption" v-model="excelForm">
        <template #excelTemplate>
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import { add, getDetail, getList, remove, update } from '@/api/vehicle/etc-record';
import { getList as getVehicleList } from '@/api/transportCapacity/transport-vehicle';
import { getDeptTree } from '@/api/system/dept';
import { exportBlob } from '@/api/common';
import { downloadXls } from '@/utils/util';
import { openImportDialog } from '@/utils/import-excel';
import { getToken } from '@/utils/auth';
import { mapGetters } from 'vuex';
import { excelOption, option } from '@/option/vehicle/etc-record';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

export default {
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      excelBox: false,
      excelForm: {},
      option,
      excelOption,
      page: {
        pageSize: 10,
        pageSizes: [10, 20, 50, 100],
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      boxType: '',
      data: [],
    };
  },
  created() {
    this.initDeptTree();
  },
  computed: {
    ...mapGetters(['permission', 'userInfo']),
    isAdmin() {
      const authority = this.userInfo.authority || '';
      return authority.includes('admin');
    },
    permissionList() {
      return {
        addBtn: this.hasPermission('etc_record_add'),
        viewBtn: this.hasPermission('etc_record_view'),
        delBtn: this.hasPermission('etc_record_delete'),
        editBtn: this.hasPermission('etc_record_edit'),
      };
    },
    ids() {
      const ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  methods: {
    hasPermission(code) {
      return this.isAdmin || this.validData(this.permission[code], false);
    },
    initDeptTree() {
      getDeptTree(this.userInfo.tenantId).then(res => {
        const column = this.findColumn(this.option.column, 'createDept');
        column.dicData = res.data.data;
      });
    },
    fetchVehicleOptions(queryString, callback) {
      getVehicleList(1, 20, { plateNo: queryString })
        .then(res => {
          const records = res.data.data.records || [];
          callback(
            records.map(item => ({
              value: item.plateNo,
            }))
          );
        })
        .catch(() => callback([]));
    },
    formatAttachments(value) {
      if (!value) return '';
      if (Array.isArray(value)) return `${value.length} 个`;
      if (typeof value !== 'string') return '1 个';
      try {
        const attachments = JSON.parse(value);
        return Array.isArray(attachments) ? `${attachments.length} 个` : '1 个';
      } catch (error) {
        return (
          value
            .split(',')
            .map(item => item.trim())
            .filter(Boolean).length + ' 个'
        );
      }
    },
    parseAttachments(value) {
      if (!value || Array.isArray(value)) return value;
      if (typeof value !== 'string') return [];
      try {
        const attachments = JSON.parse(value);
        return Array.isArray(attachments) ? attachments : [];
      } catch (error) {
        return value
          .split(',')
          .map(item => ({ name: item.trim(), url: item.trim() }))
          .filter(item => item.url);
      }
    },
    stringifyAttachments(value) {
      if (!value || typeof value === 'string') return value;
      return JSON.stringify(value);
    },
    isEmpty(value) {
      return value === undefined || value === null || value === '';
    },
    normalizeDecimalInput(prop, value) {
      const sanitized = String(value ?? '').replace(/[^\d.]/g, '');
      const [integerPart, ...decimalParts] = sanitized.split('.');
      this.form[prop] = decimalParts.length
        ? `${integerPart || '0'}.${decimalParts.join('').slice(0, 2)}`
        : integerPart;
    },
    normalizeRow(row) {
      const values = { ...row };
      values.dataSource = values.dataSource || '手工录入';
      if (values.vehicleNo) {
        values.vehicleNo = values.vehicleNo.trim().toUpperCase();
      }
      if (values.etcCardNo) {
        values.etcCardNo = values.etcCardNo.trim();
      }
      values.attachments = this.stringifyAttachments(values.attachments);
      return values;
    },
    validateDecimal(value, label, required = false) {
      if (this.isEmpty(value)) {
        if (required) {
          this.$message.warning(`请输入${label}`);
          return false;
        }
        return true;
      }
      if (Number(value) < 0) {
        this.$message.warning(`${label}不能小于 0`);
        return false;
      }
      if (!/^\d+(\.\d{1,2})?$/.test(String(value))) {
        this.$message.warning(`${label}最多保留 2 位小数`);
        return false;
      }
      return true;
    },
    validateRow(row) {
      if (row.entryTime && row.exitTime && new Date(row.exitTime) <= new Date(row.entryTime)) {
        this.$message.warning('出口时间应大于入口时间');
        return false;
      }
      if (!this.validateDecimal(row.transactionAmount, '交易金额', true)) return false;
      if (row.remark && row.remark.length > 200) {
        this.$message.warning('备注不能超过 200 字');
        return false;
      }
      return true;
    },
    rowSave(row, done, loading) {
      const values = this.normalizeRow(row);
      if (!this.validateRow(values)) {
        loading();
        return;
      }
      add(values).then(
        () => {
          this.onLoad(this.page);
          this.$message({ type: 'success', message: '操作成功!' });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      const values = this.normalizeRow(row);
      if (!this.validateRow(values)) {
        loading();
        return;
      }
      update(values).then(
        () => {
          this.onLoad(this.page);
          this.$message({ type: 'success', message: '操作成功!' });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => remove(row.id))
        .then(() => {
          this.onLoad(this.page);
          this.$message({ type: 'success', message: '操作成功!' });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => remove(this.ids))
        .then(() => {
          this.onLoad(this.page);
          this.$message({ type: 'success', message: '操作成功!' });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      this.boxType = type;
      if (type === 'add') {
        this.form = { dataSource: '手工录入' };
      }
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          const detail = res.data.data;
          detail.attachments = this.parseAttachments(detail.attachments);
          this.form = detail;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, { ...params, ...this.query })
        .then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.selectionClear();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleImport() {
      openImportDialog(this, 'ETC记录');
    },
    handleExport() {
      this.$confirm('是否导出ETC记录数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        NProgress.start();
        exportBlob('/blade-transport/etc-record/export-etc-record', this.buildExportParams(), {
          feedback: true,
        })
          .then(res => {
            downloadXls(res.data, `ETC记录${this.$dayjs().format('YYYY-MM-DD HH:mm:ss')}.xlsx`);
          })
          .finally(() => {
            NProgress.done();
          });
      });
    },
    buildExportParams() {
      return {
        ...this.query,
        ids: this.ids,
        [this.website.tokenHeader]: getToken(),
      };
    },
    handleTemplate() {
      exportBlob(
        `/blade-transport/etc-record/export-template?${this.website.tokenHeader}=${getToken()}`,
        { feedback: true }
      ).then(res => {
        downloadXls(res.data, 'ETC记录模板.xlsx');
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.etc-record-page {
  :deep(.el-table th .cell),
  :deep(.el-table td .cell) {
    white-space: nowrap;
  }

  &__input {
    width: 100%;
  }
}
</style>
