<template>
  <basic-container class="maintenance-plan-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('maintenance_plan_import')"
          @click="handleImport"
          >批量导入
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          plain
          v-if="hasPermission('maintenance_plan_template')"
          @click="handleTemplate"
          >下载模板
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          plain
          v-if="hasPermission('maintenance_plan_export')"
          @click="handleExport"
          >批量导出
        </el-button>
        <el-button
          type="danger"
          icon="el-icon-delete"
          plain
          v-if="hasPermission('maintenance_plan_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="vehicleNoPlaceholder"
          value-key="value"
          class="maintenance-plan-page__input"
        />
      </template>
      <template #mileage="{ row }">
        <span>{{ formatMileage(row.mileage, row.mileageUnit) }}</span>
      </template>
      <template #nextMaintenanceMileage="{ row }">
        <span>{{ formatMileage(row.nextMaintenanceMileage, row.mileageUnit) }}</span>
      </template>
      <template #attachments="{ row }">
        <span>{{ formatAttachments(row.attachments) }}</span>
      </template>
      <template #attachmentsForm>
        <vehicle-attachment-upload
          v-model="form.attachments"
          :readonly="boxType === 'view'"
          button-text="新增"
          button-icon="el-icon-plus"
          :show-tip="false"
        />
      </template>
      <template #attachments-form>
        <vehicle-attachment-upload
          v-model="form.attachments"
          :readonly="boxType === 'view'"
          button-text="新增"
          button-icon="el-icon-plus"
          :show-tip="false"
        />
      </template>
    </avue-crud>
    <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 { getList, getDetail, add, update, remove } from '@/api/vehicle/maintenance-plan';
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 { formatUpdateUserName } from '@/utils/audit';
import { getToken } from '@/utils/auth';
import { normalizeSearchRangeParams } from '@/utils/search-range';
import { mapGetters } from 'vuex';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

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

export default {
  data() {
    const validateNonNegative = (rule, value, callback) => {
      if (value === undefined || value === null || value === '') {
        callback();
      } else if (Number(value) < 0) {
        callback(new Error('不能小于 0'));
      } else {
        callback();
      }
    };
    return {
      form: {},
      query: {},
      loading: true,
      excelBox: false,
      excelForm: {},
      page: {
        pageSize: 10,
        pageSizes: [10, 20, 50, 100],
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      boxType: '',
      option: {
        height: 'auto',
        calcHeight: 32,
        dialogWidth: 960,
        labelPosition: 'right',
        labelWidth: 'auto',
        searchLabelWidth: 160,
        tip: false,
        searchShow: true,
        searchMenuSpan: 24,
        searchIcon: true,
        searchIndex: 4,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        dialogClickModal: false,
        menuWidth: 160,
        column: [
          {
            label: '车船类型',
            prop: 'vehicleType',
            type: 'radio',
            minWidth: 110,
            dicData: [
              { label: '车辆', value: '车辆' },
              { label: '船舶', value: '船舶' },
            ],
            value: '车辆',
            search: true,
            span: 24,
            change: ({ value }) => this.handleVehicleTypeChange(value || '车辆'),
            rules: [{ required: true, message: '请选择车船类型', trigger: 'change' }],
          },
          {
            label: '车牌号/船号',
            prop: 'vehicleNo',
            slot: true,
            search: true,
            minWidth: 130,
            span: 12,
            placeholder: '输入车牌号/船号查询选择',
            rules: [
              { required: true, message: '请输入车牌号/船号', trigger: 'blur' },
              { max: 30, message: '最多 30 个字符', trigger: 'blur' },
            ],
          },
          {
            label: '保养人',
            prop: 'maintainer',
            span: 12,
            placeholder: '请输入',
            rules: [{ max: 20, message: '最多 20 个字符', trigger: 'blur' }],
          },
          {
            label: '保养时间',
            prop: 'maintenanceTime',
            type: 'date',
            format: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            minWidth: 170,
            span: 12,
            placeholder: '请选择',
            rules: [{ required: true, message: '请选择保养时间', trigger: 'click' }],
          },
          {
            label: '里程/航程数',
            prop: 'mileage',
            type: 'number',
            precision: 2,
            minWidth: 130,
            slot: true,
            span: 12,
            append: '公里',
            placeholder: '请输入',
            rules: [{ validator: validateNonNegative, trigger: 'blur' }],
          },
          {
            label: '里程单位',
            prop: 'mileageUnit',
            type: 'select',
            dicData: [
              { label: '公里', value: '公里' },
              { label: '海里', value: '海里' },
            ],
            value: '公里',
            hide: true,
            display: false,
          },
          {
            label: '保养项目',
            prop: 'maintenanceItem',
            minWidth: 160,
            span: 12,
            placeholder: '请输入',
            rules: [{ max: 100, message: '最多 100 个字符', trigger: 'blur' }],
          },
          {
            label: '费用',
            prop: 'cost',
            type: 'number',
            precision: 2,
            append: '元',
            span: 12,
            placeholder: '请输入',
            rules: [
              { required: true, message: '请输入费用', trigger: 'blur' },
              { validator: validateNonNegative, trigger: 'blur' },
            ],
          },
          {
            label: '店名',
            prop: 'storeName',
            span: 12,
            placeholder: '请输入',
            rules: [{ max: 50, message: '最多 50 个字符', trigger: 'blur' }],
          },
          {
            label: '联系电话',
            prop: 'contactPhone',
            minWidth: 150,
            span: 12,
            placeholder: '请输入',
            rules: [{ max: 20, message: '最多 20 个字符', trigger: 'blur' }],
          },
          {
            label: '地址',
            prop: 'address',
            minWidth: 180,
            overHidden: true,
            span: 24,
            placeholder: '地图选址',
            rules: [{ max: 100, message: '最多 100 个字符', trigger: 'blur' }],
          },
          {
            label: '下次保养时间',
            prop: 'nextMaintenanceTime',
            type: 'date',
            format: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            minWidth: 170,
            span: 12,
            placeholder: '请选择',
          },
          {
            label: '下次保养里程/航程',
            prop: 'nextMaintenanceMileage',
            type: 'number',
            precision: 2,
            minWidth: 170,
            slot: true,
            span: 12,
            append: '公里',
            placeholder: '请输入',
            rules: [{ validator: validateNonNegative, trigger: 'blur' }],
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            minRows: 5,
            span: 24,
            hide: true,
            placeholder: '请输入',
            rules: [{ max: 500, message: '最多 500 个字符', trigger: 'blur' }],
          },
          {
            label: '附件',
            prop: 'attachments',
            span: 24,
            minWidth: 100,
            slot: true,
            formslot: true,
          },
          {
            label: '创建时间',
            prop: 'createTime',
            type: 'date',
            format: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            display: false,
            minWidth: 170,
          },
          {
            label: '创建时间',
            prop: 'createTimeRange',
            type: 'date',
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            searchRange: true,
            search: true,
            hide: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
          },
          {
            label: '组织',
            prop: 'createDept',
            type: 'tree',
            dicData: [],
            props: {
              label: 'title',
              value: 'id',
            },
            checkStrictly: true,
            search: true,
            hide: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
          },
          {
            label: '更新人',
            prop: 'updateUserName',
            formatter: formatUpdateUserName,
            addDisplay: false,
            editDisplay: false,
            display: false,
            minWidth: 180,
          },
          {
            label: '更新时间',
            prop: 'updateTime',
            type: 'datetime',
            format: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            addDisplay: false,
            editDisplay: false,
            display: false,
            minWidth: 170,
          },
        ],
      },
      excelOption: {
        labelPosition: 'right',
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '模板上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '模板上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data',
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: '/blade-transport/maintenance-plan/import-maintenance-plan',
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          },
        ],
      },
      data: [],
    };
  },
  created() {
    this.initDeptTree();
  },
  computed: {
    ...mapGetters(['permission', 'userInfo']),
    isAdmin() {
      const authority = this.userInfo.authority || '';
      return authority.includes('admin');
    },
    permissionList() {
      return {
        addBtn: this.hasPermission('maintenance_plan_add'),
        viewBtn: this.hasPermission('maintenance_plan_view'),
        delBtn: this.hasPermission('maintenance_plan_delete'),
        editBtn: this.hasPermission('maintenance_plan_edit'),
      };
    },
    vehicleNoPlaceholder() {
      return this.form.vehicleType === '船舶' ? '输入船号模糊查询选择' : '输入车牌号模糊查询选择';
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  methods: {
    hasPermission(code) {
      return this.isAdmin || this.validData(this.permission[code], false);
    },
    handleVehicleTypeChange(vehicleType) {
      this.updateVehicleType(vehicleType);
      if (!this.form.id && this.form.vehicleNo) {
        this.form.vehicleNo = '';
      }
    },
    updateVehicleType(vehicleType) {
      const mileageUnit = vehicleType === '船舶' ? '海里' : '公里';
      const mileageColumn = this.findColumn(this.option.column, 'mileage');
      const nextMaintenanceMileageColumn = this.findColumn(
        this.option.column,
        'nextMaintenanceMileage'
      );
      const mileageUnitColumn = this.findColumn(this.option.column, 'mileageUnit');
      mileageColumn.append = mileageUnit;
      nextMaintenanceMileageColumn.append = mileageUnit;
      mileageUnitColumn.value = mileageUnit;
      this.form.mileageUnit = mileageUnit;
    },
    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 (value === undefined || value === null || value === '') return '';
      return `${Math.max(Number(value), 0)} ${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 + ' 个'
        );
      }
    },
    isEmpty(value) {
      return value === undefined || value === null || value === '';
    },
    toNumber(value) {
      return this.isEmpty(value) ? null : Number(value);
    },
    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);
    },
    initDeptTree() {
      getDeptTree(this.userInfo.tenantId).then(res => {
        const column = this.findColumn(this.option.column, 'createDept');
        column.dicData = res.data.data;
      });
    },
    normalizeRow(row) {
      const values = { ...row };
      values.vehicleType = values.vehicleType || '车辆';
      values.mileageUnit = values.vehicleType === '船舶' ? '海里' : '公里';
      values.attachments = this.stringifyAttachments(values.attachments);
      return values;
    },
    validateRow(row) {
      const mileage = this.toNumber(row.mileage);
      const nextMaintenanceMileage = this.toNumber(row.nextMaintenanceMileage);
      if (
        mileage !== null &&
        nextMaintenanceMileage !== null &&
        nextMaintenanceMileage <= mileage
      ) {
        this.$message.warning('下次保养里程/航程应大于本次里程/航程数');
        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.vehicleType = '车辆';
        this.form.mileageUnit = '公里';
        this.updateVehicleType(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 || '车辆';
          detail.mileageUnit = detail.vehicleType === '船舶' ? '海里' : '公里';
          this.form = detail;
          this.updateVehicleType(detail.vehicleType);
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      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/maintenance-plan/export-maintenance-plan',
          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/maintenance-plan/export-template?${
          this.website.tokenHeader
        }=${getToken()}`,
        { feedback: true }
      ).then(res => {
        downloadXls(res.data, '保养记录模板.xlsx');
      });
    },
  },
};
</script>

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

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