<template>
  <basic-container class="equipment-ledger-page">
    <avue-crud
      ref="crud"
      v-model="form"
      v-model:page="page"
      :option="option"
      :data="data"
      :permission="permissionList"
      :table-loading="loading"
      :before-open="beforeOpen"
      @row-save="rowSave"
      @row-update="rowUpdate"
      @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
          v-if="hasPermission('equipment_ledger_import')"
          type="primary"
          plain
          @click="handleImport"
        >
          批量导入
        </el-button>
        <el-button
          v-if="hasPermission('equipment_ledger_template')"
          type="primary"
          plain
          @click="handleTemplate"
        >
          下载模板
        </el-button>
        <el-button
          v-if="hasPermission('equipment_ledger_export')"
          type="primary"
          plain
          @click="handleExport"
        >
          批量导出
        </el-button>
      </template>
      <template #vehicleNo="{ row, index }">
        <el-link type="primary" @click="$refs.crud.rowView(row, index)">{{
          row.vehicleNo
        }}</el-link>
      </template>
      <template #vehicleNoForm>
        <el-autocomplete
          v-model="form.vehicleNo"
          :disabled="boxType === 'view'"
          :fetch-suggestions="fetchVehicleOptions"
          :placeholder="vehicleNoPlaceholder"
          clearable
          value-key="value"
        />
      </template>
      <template #equipmentCodeForm>
        <el-input v-model="form.equipmentCode" disabled />
      </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">点击下载</el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

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

export default {
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      excelBox: false,
      excelForm: {},
      boxType: '',
      option,
      excelOption,
      data: [],
      selectionList: [],
      page: { pageSize: 10, pageSizes: [10, 20, 50, 100], currentPage: 1, total: 0 },
    };
  },
  computed: {
    ...mapGetters(['permission', 'userInfo']),
    isAdmin() {
      return (this.userInfo.authority || '').includes('admin');
    },
    permissionList() {
      return {
        addBtn: this.hasPermission('equipment_ledger_add'),
        viewBtn: this.hasPermission('equipment_ledger_view'),
        editBtn: this.hasPermission('equipment_ledger_edit'),
        delBtn: this.hasPermission('equipment_ledger_delete'),
      };
    },
    vehicleNoPlaceholder() {
      return this.form.vehicleType === '船舶' ? '输入船号模糊查询选择' : '输入车牌号模糊查询选择';
    },
    ids() {
      return this.selectionList.map(item => item.id).join(',');
    },
  },
  created() {
    this.initDeptTree();
    this.initEquipmentTypeOptions();
  },
  methods: {
    hasPermission(code) {
      return this.isAdmin || this.validData(this.permission[code], false);
    },
    initDeptTree() {
      getDeptTree(this.userInfo.tenantId).then(res => {
        this.findColumn(this.option.column, 'createDept').dicData = res.data.data || [];
      });
    },
    initEquipmentTypeOptions() {
      getDictionary({ code: 'equip_type' }).then(res => {
        this.findColumn(this.option.column, 'equipmentType').dicData = (res.data.data || []).map(
          item => ({
            label: item.dictValue,
            value: item.dictValue,
          })
        );
      });
    },
    fetchVehicleOptions(queryString, callback) {
      const isShip = this.form.vehicleType === '船舶';
      const request = isShip ? getShipList : getVehicleList;
      const params = isShip ? { shipIdentifierNo: queryString } : { plateNo: queryString };
      request(1, 20, params)
        .then(res => {
          callback(
            (res.data.data.records || []).map(item => ({
              value: isShip ? item.shipIdentifierNo || item.shipName : item.plateNo,
            }))
          );
        })
        .catch(() => callback([]));
    },
    formatAttachments(value) {
      if (!value) return '';
      if (Array.isArray(value)) return `${value.length} 个`;
      try {
        const attachments = JSON.parse(value);
        return Array.isArray(attachments) ? `${attachments.length} 个` : '1 个';
      } catch (error) {
        return `${value.split(',').filter(Boolean).length} 个`;
      }
    },
    parseAttachments(value) {
      if (!value || Array.isArray(value)) return value;
      try {
        const attachments = JSON.parse(value);
        return Array.isArray(attachments) ? attachments : [];
      } catch (error) {
        return value
          .split(',')
          .filter(Boolean)
          .map(url => ({ name: url, url }));
      }
    },
    normalizeRow(row) {
      const values = { ...row };
      values.vehicleType = values.vehicleType || '车辆';
      values.vehicleNo = (values.vehicleNo || '').trim();
      if (values.vehicleType === '车辆') values.vehicleNo = values.vehicleNo.toUpperCase();
      values.attachments = Array.isArray(values.attachments)
        ? JSON.stringify(values.attachments)
        : values.attachments;
      return values;
    },
    rowSave(row, done, loading) {
      add(this.normalizeRow(row)).then(
        () => {
          this.onLoad(this.page);
          this.$message.success('操作成功');
          done();
        },
        () => loading()
      );
    },
    rowUpdate(row, index, done, loading) {
      update(this.normalizeRow(row)).then(
        () => {
          this.onLoad(this.page);
          this.$message.success('操作成功');
          done();
        },
        () => loading()
      );
    },
    rowDel(row) {
      this.$confirm('确认删除该条数据？删除后将不可恢复！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => remove(row.id))
        .then(() => {
          this.onLoad(this.page);
          this.$message.success('操作成功');
        });
    },
    beforeOpen(done, type) {
      this.boxType = type;
      if (type === 'add') {
        getNextEquipmentCode().then(res => {
          this.form = { vehicleType: '车辆', equipmentCode: res.data.data };
          done();
        });
        return;
      }
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = {
            ...res.data.data,
            attachments: this.parseAttachments(res.data.data.attachments),
          };
          done();
        });
        return;
      }
      done();
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    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.query, ...params })
        .then(res => {
          const result = res.data.data;
          this.page.total = result.total;
          this.data = result.records;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleImport() {
      openImportDialog(this, '设备台账');
    },
    handleExport() {
      this.$confirm('是否导出设备台账数据？', '提示', { type: 'warning' }).then(() => {
        NProgress.start();
        exportBlob(
          '/blade-transport/equipment-ledger/export-equipment-ledger',
          { ...this.query, ids: this.ids, [this.website.tokenHeader]: getToken() },
          { feedback: true }
        )
          .then(res =>
            downloadXls(res.data, `设备台账${this.$dayjs().format('YYYY-MM-DD HH:mm:ss')}.xlsx`)
          )
          .finally(() => NProgress.done());
      });
    },
    handleTemplate() {
      exportBlob(
        `/blade-transport/equipment-ledger/export-template?${
          this.website.tokenHeader
        }=${getToken()}`,
        { feedback: true }
      ).then(res => downloadXls(res.data, '设备台账模板.xlsx'));
    },
  },
};
</script>

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