<template>
  <basic-container class="mileage-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('mileage_record_import')"
          @click="handleImport"
          >批量导入
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          plain
          v-if="hasPermission('mileage_record_template')"
          @click="handleTemplate"
          >下载模板
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          plain
          v-if="hasPermission('mileage_record_export')"
          @click="handleExport"
          >批量导出
        </el-button>
        <el-button
          type="danger"
          icon="el-icon-delete"
          plain
          v-if="hasPermission('mileage_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 #previousMonthMileage="{ row }">
        <span>{{ formatMileage(row.previousMonthMileage, row.mileageUnit) }}</span>
      </template>
      <template #currentMonthMileage="{ row }">
        <span>{{ formatMileage(row.currentMonthMileage, row.mileageUnit) }}</span>
      </template>
      <template #monthlyMileage="{ row }">
        <span>{{ formatMileage(row.monthlyMileage, row.mileageUnit) }}</span>
      </template>
      <template #totalMileage="{ row }">
        <span>{{ formatMileage(row.totalMileage, row.mileageUnit) }}</span>
      </template>
      <template #vehicleNoForm>
        <el-autocomplete
          v-model="form.vehicleNo"
          :fetch-suggestions="fetchVehicleOptions"
          :disabled="Boolean(form.id)"
          clearable
          :placeholder="vehicleNoPlaceholder"
          value-key="value"
          class="mileage-record-page__input"
        />
      </template>
      <template #previousMonthMileageForm>
        <el-input
          v-model="form.previousMonthMileage"
          :disabled="boxType === 'view'"
          inputmode="numeric"
          placeholder="请输入"
          @input="value => normalizeIntegerInput('previousMonthMileage', value)"
        >
          <template #suffix>km</template>
        </el-input>
      </template>
      <template #currentMonthMileageForm>
        <el-input
          v-model="form.currentMonthMileage"
          :disabled="boxType === 'view'"
          inputmode="numeric"
          placeholder="请输入"
          @input="value => normalizeIntegerInput('currentMonthMileage', value)"
        >
          <template #suffix>km</template>
        </el-input>
      </template>
      <template #monthlyMileageForm>
        <el-input
          v-model="form.monthlyMileage"
          :disabled="boxType === 'view'"
          inputmode="numeric"
          placeholder="请输入"
          @input="value => normalizeIntegerInput('monthlyMileage', value)"
        >
          <template #suffix>km</template>
        </el-input>
      </template>
      <template #totalMileageForm>
        <el-input
          v-model="form.totalMileage"
          :disabled="boxType === 'view'"
          inputmode="numeric"
          placeholder="请输入"
          @input="value => normalizeIntegerInput('totalMileage', value)"
        >
          <template #suffix>km</template>
        </el-input>
      </template>
      <template #totalMileageStart-search="{ row }">
        <div class="mileage-record-page__range">
          <el-input
            v-model="row.totalMileageStart"
            clearable
            placeholder="请输入"
            type="number"
            class="mileage-record-page__range-input"
          />
          <span class="mileage-record-page__range-separator">-</span>
          <el-input
            v-model="row.totalMileageEnd"
            clearable
            placeholder="请输入"
            type="number"
            class="mileage-record-page__range-input"
          />
        </div>
      </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>
    <empty-pagination
      :page="page"
      @size-change="sizeChange"
      @current-change="currentChange"
      @load="onLoad(page, query)"
    />
    <el-dialog title="里程记录数据导入" 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/mileage-record';
import { getList as getVehicleList } from '@/api/transportCapacity/transport-vehicle';
import { getList as getShipList } from '@/api/transportCapacity/transport-ship';
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 { normalizeSearchRangeParams } from '@/utils/search-range';
import { mapGetters } from 'vuex';
import { excelOption, option } from '@/option/vehicle/mileage-record';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

const createTimeRangeMap = {
  createTimeRange: ['createTimeStart', 'createTimeEnd'],
};

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('mileage_record_add'),
        viewBtn: this.hasPermission('mileage_record_view'),
        delBtn: this.hasPermission('mileage_record_delete'),
        editBtn: this.hasPermission('mileage_record_edit'),
      };
    },
    vehicleNoPlaceholder() {
      return this.form.vehicleType === '船舶' ? '输入船号模糊查询选择' : '输入车牌号模糊查询选择';
    },
    ids() {
      const ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  watch: {
    'form.vehicleType': {
      handler(value) {
        this.updateVehicleTypeDisplays(value || '车辆');
      },
      immediate: true,
    },
  },
  methods: {
    hasPermission(code) {
      return this.isAdmin || this.validData(this.permission[code], false);
    },
    updateVehicleTypeDisplays(vehicleType) {
      const isShip = vehicleType === '船舶';
      const unit = isShip ? '海里' : '公里';
      const vehicleTypeColumn = this.findColumn(this.option.column, 'vehicleType');
      const labelMap = {
        previousMonthMileage: isShip ? '上月统计航程数' : '上月统计里程数',
        currentMonthMileage: isShip ? '本月统计航程数' : '本月统计里程数',
        monthlyMileage: isShip ? '本月航行航程数' : '本月行驶里程数',
        totalMileage: isShip ? '累计航程数' : '累计行驶里程数',
        totalMileageStart: isShip ? '累计航程' : '累计行驶里程',
        totalMileageEnd: isShip ? '累计航程数结束值' : '累计行驶里程数结束值',
      };
      Object.keys(labelMap).forEach(prop => {
        const column = this.findColumn(this.option.column, prop);
        column.label = labelMap[prop];
      });
      vehicleTypeColumn.disabled = Boolean(this.form.id);
      const unitColumn = this.findColumn(this.option.column, 'mileageUnit');
      unitColumn.value = unit;
      this.form.mileageUnit = unit;
      if (!this.form.id && this.form.vehicleNo) {
        this.form.vehicleNo = '';
      }
    },
    initDeptTree() {
      getDeptTree(this.userInfo.tenantId).then(res => {
        const column = this.findColumn(this.option.column, 'createDept');
        column.dicData = res.data.data;
      });
    },
    fetchVehicleOptions(queryString, callback) {
      const vehicleType = this.form.vehicleType || '车辆';
      const request = vehicleType === '船舶' ? getShipList : getVehicleList;
      const params =
        vehicleType === '船舶' ? { shipIdentifierNo: queryString } : { plateNo: queryString };
      request(1, 20, params)
        .then(res => {
          const records = res.data.data.records || [];
          callback(
            records.map(item => ({
              value: vehicleType === '船舶' ? item.shipIdentifierNo || item.shipName : item.plateNo,
            }))
          );
        })
        .catch(() => callback([]));
    },
    formatMileage(value, unit) {
      if (this.isEmpty(value)) {
        return '';
      }
      return `${value} ${unit || '公里'}`;
    },
    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 === '';
    },
    toNumber(value) {
      return this.isEmpty(value) ? null : Number(value);
    },
    toMoney(value) {
      return Math.round(Number(value) * 100) / 100;
    },
    normalizeIntegerInput(prop, value) {
      this.form[prop] = String(value ?? '').replace(/\D/g, '');
    },
    normalizeRow(row) {
      const values = { ...row };
      values.vehicleType = values.vehicleType || '车辆';
      values.mileageUnit = values.vehicleType === '船舶' ? '海里' : '公里';
      if (values.vehicleNo) {
        values.vehicleNo =
          values.vehicleType === '船舶'
            ? values.vehicleNo.trim()
            : values.vehicleNo.trim().toUpperCase();
      }
      const previousMonthMileage = this.toNumber(values.previousMonthMileage);
      const currentMonthMileage = this.toNumber(values.currentMonthMileage);
      if (
        this.isEmpty(values.monthlyMileage) &&
        previousMonthMileage !== null &&
        currentMonthMileage !== null
      ) {
        values.monthlyMileage = this.toMoney(currentMonthMileage - previousMonthMileage);
      }
      values.attachments = this.stringifyAttachments(values.attachments);
      return values;
    },
    validateMileage(value, label) {
      if (this.isEmpty(value)) {
        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) {
      const isShip = row.vehicleType === '船舶';
      const mileageFields = [
        ['previousMonthMileage', isShip ? '上月统计航程数' : '上月统计里程数'],
        ['currentMonthMileage', isShip ? '本月统计航程数' : '本月统计里程数'],
        ['monthlyMileage', isShip ? '本月航行航程数' : '本月行驶里程数'],
        ['totalMileage', isShip ? '累计航程数' : '累计行驶里程数'],
      ];
      if (!mileageFields.every(([prop, label]) => this.validateMileage(row[prop], label))) {
        return false;
      }
      const previousMonthMileage = this.toNumber(row.previousMonthMileage);
      const currentMonthMileage = this.toNumber(row.currentMonthMileage);
      const monthlyMileage = this.toNumber(row.monthlyMileage);
      const totalMileage = this.toNumber(row.totalMileage);
      if (
        previousMonthMileage !== null &&
        currentMonthMileage !== null &&
        monthlyMileage !== null &&
        this.toMoney(currentMonthMileage - previousMonthMileage) !== this.toMoney(monthlyMileage)
      ) {
        this.$message.warning(
          isShip
            ? '本月航行航程数应等于本月统计航程数减去上月统计航程数'
            : '本月行驶里程数应等于本月统计里程数减去上月统计里程数'
        );
        return false;
      }
      if (
        totalMileage !== null &&
        currentMonthMileage !== null &&
        totalMileage < currentMonthMileage
      ) {
        this.$message.warning(
          isShip ? '累计航程数应大于等于本月统计航程数' : '累计行驶里程数应大于等于本月统计里程数'
        );
        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;
      const vehicleNoColumn = this.findColumn(this.option.column, 'vehicleNo');
      vehicleNoColumn.disabled = type !== 'add';
      if (type === 'add') {
        this.form.vehicleType = '车辆';
        this.form.mileageUnit = '公里';
        this.updateVehicleTypeDisplays(this.form.vehicleType);
      }
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          const detail = res.data.data;
          detail.attachments = this.parseAttachments(detail.attachments);
          detail.vehicleType = detail.vehicleType || this.form.vehicleType || '车辆';
          detail.mileageUnit = detail.vehicleType === '船舶' ? '海里' : '公里';
          this.form = detail;
          this.updateVehicleTypeDisplays(detail.vehicleType);
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      if (this.$refs.crud?.search) {
        this.$refs.crud.search.createTimeRange = undefined;
        this.$refs.crud.search.totalMileageStart = undefined;
        this.$refs.crud.search.totalMileageEnd = undefined;
      }
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = this.buildQuery(params);
      this.page.currentPage = 1;
      this.onLoad(this.page);
      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, this.buildQuery(params))
        .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, '里程记录');
    },
    handleExport() {
      this.$confirm('是否导出里程记录数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        NProgress.start();
        exportBlob(
          '/blade-transport/mileage-record/export-mileage-record',
          this.buildExportParams(),
          { feedback: true }
        )
          .then(res => {
            downloadXls(res.data, `里程记录${this.$dayjs().format('YYYY-MM-DD HH:mm:ss')}.xlsx`);
          })
          .finally(() => {
            NProgress.done();
          });
      });
    },
    buildExportParams() {
      return {
        ...this.buildQuery(),
        ids: this.ids,
        [this.website.tokenHeader]: getToken(),
      };
    },
    buildQuery(params = {}) {
      return normalizeSearchRangeParams({ ...params, ...this.query }, createTimeRangeMap);
    },
    handleTemplate() {
      exportBlob(
        `/blade-transport/mileage-record/export-template?${this.website.tokenHeader}=${getToken()}`,
        { feedback: true }
      ).then(res => {
        downloadXls(res.data, '里程记录模板.xlsx');
      });
    },
  },
};
</script>

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

  &__input {
    width: 100%;
  }

  &__range {
    display: flex;
    align-items: center;
    gap: 8px;
    width: 100%;
  }

  &__range-input {
    width: 150px;
  }

  &__range-separator {
    color: #606266;
    line-height: 32px;
  }
}
</style>
