<template>
  <basic-container class="port-terminal-page">
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model:page="page"
      v-model="form"
      ref="crud"
      :permission="permissionList"
      :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
          type="primary"
          icon="el-icon-upload"
          plain
          v-if="hasPermission('port_terminal_import')"
          @click="handleImport"
          >批量导入
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          plain
          v-if="hasPermission('port_terminal_template')"
          @click="handleTemplate"
          >下载模板
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          plain
          v-if="hasPermission('port_terminal_export')"
          @click="handleExport"
          >批量导出
        </el-button>
        <el-button
          type="danger"
          icon="el-icon-delete"
          plain
          v-if="hasPermission('port_terminal_delete')"
          @click="handleDelete"
          >批量删除
        </el-button>
      </template>
      <template #parentName="{ row }">
        <span>{{ row.category === '港口' ? '-' : row.parentName }}</span>
      </template>
      <template #parentCode="{ row }">
        <span>{{ row.category === '港口' ? '-' : row.parentCode }}</span>
      </template>
      <template #status="{ row }">
        <el-tag :type="row.status === 1 ? 'primary' : 'info'">
          {{ row.status === 1 ? '启用' : '停用' }}
        </el-tag>
      </template>
      <template #menu="{ row, index }">
        <el-button
          type="primary"
          text
          icon="el-icon-edit"
          v-if="hasPermission('port_terminal_edit')"
          @click="$refs.crud.rowEdit(row, index)"
        >
          编辑
        </el-button>
        <el-button
          type="primary"
          text
          :icon="row.status === 1 ? 'el-icon-close' : 'el-icon-check'"
          v-if="hasPermission('port_terminal_status')"
          @click="handleStatus(row)"
        >
          {{ row.status === 1 ? '停用' : '启用' }}
        </el-button>
      </template>
      <template #regionCode-form>
        <el-cascader
          v-model="form.regionCode"
          :props="regionProps"
          clearable
          filterable
          :disabled="isParentRegionLocked"
          style="width: 100%"
          @change="handleRegionChange"
        />
      </template>
    </avue-crud>

    <el-dialog title="港口码头主数据导入" append-to-body v-model="excelBox" width="555px">
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-before="uploadBefore"
        :upload-after="uploadAfter"
      >
        <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,
  submit,
  remove,
  changeStatus,
  getPortSelect,
} from '@/api/base/port-terminal';
import { getLazyTree } from '@/api/base/region';
import { exportBlob } from '@/api/common';
import { mapGetters } from 'vuex';
import { downloadXls } from '@/utils/util';
import { formatUpdateUserName } from '@/utils/audit';
import { getToken } from '@/utils/auth';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

export default {
  data() {
    const validateCode = (rule, value, callback) => {
      const code = String(value || '').toUpperCase();
      if (this.form.category === '港口') {
        if (!/^[A-Z]{5}$/.test(code)) {
          callback(new Error('港口编码为5位大写字母，如：CNSHG'));
        } else {
          callback();
        }
        return;
      }
      if (this.form.category === '码头') {
        if (!/^[A-Z]{5}-[A-Z0-9]+$/.test(code)) {
          callback(new Error('码头编码格式为“港口编码-码头标识”，如：CNSHG-CT1'));
        } else if (this.form.parentCode && !code.startsWith(`${this.form.parentCode}-`)) {
          callback(new Error(`码头编码须以所选上级港口编码 ${this.form.parentCode}- 开头`));
        } else {
          callback();
        }
        return;
      }
      callback();
    };
    const validateLongitude = (rule, value, callback) => {
      if (value === undefined || value === null || value === '') {
        callback();
      } else if (Number(value) < -180 || Number(value) > 180) {
        callback(new Error('经度范围为 -180 到 180'));
      } else {
        callback();
      }
    };
    const validateLatitude = (rule, value, callback) => {
      if (value === undefined || value === null || value === '') {
        callback();
      } else if (Number(value) < -90 || Number(value) > 90) {
        callback(new Error('纬度范围为 -90 到 90'));
      } else {
        callback();
      }
    };
    return {
      form: {},
      query: {},
      loading: true,
      data: [],
      excelBox: false,
      excelForm: {},
      portOptions: [],
      regionNodeMap: {},
      regionNameMap: {},
      regionProps: {
        lazy: true,
        lazyLoad: this.loadRegionNode,
        label: 'title',
        value: 'id',
        checkStrictly: false,
        emitPath: true,
      },
      page: {
        pageSize: 10,
        pageSizes: [10, 20, 50, 100],
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 32,
        dialogWidth: 980,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        indexWidth: 70,
        viewBtn: false,
        delBtn: false,
        editBtn: false,
        selection: true,
        dialogClickModal: false,
        menuWidth: 160,
        column: [
          {
            label: '编码',
            prop: 'code',
            search: true,
            width: 140,
            placeholder: '港口如 CNSHG，码头如 CNSHG-CT1',
            rules: [
              { required: true, message: '请输入编码', trigger: 'blur' },
              { validator: validateCode, trigger: 'blur' },
            ],
            change: ({ value }) => this.handleCodeChange(value),
            blur: ({ value }) => this.handleCodeChange(value),
          },
          {
            label: '港口/码头名称',
            prop: 'name',
            minWidth: 140,
            search: true,
            rules: [{ required: true, message: '请输入港口/码头名称', trigger: 'blur' }],
          },
          {
            label: '类型',
            prop: 'category',
            type: 'select',
            search: true,
            dicData: [
              { label: '全部', value: '' },
              { label: '港口', value: '港口' },
              { label: '码头', value: '码头' },
            ],
            rules: [{ required: true, message: '请选择类型', trigger: 'change' }],
            change: ({ value }) => this.handleCategoryChange(value),
          },
          {
            label: '上级港口',
            prop: 'parentId',
            type: 'select',
            props: {
              label: 'name',
              value: 'id',
            },
            dicData: [],
            hide: true,
            rules: [{ required: false, message: '请选择上级港口', trigger: 'change' }],
            change: ({ value }) => this.handleParentChange(value),
          },
          {
            label: '上级港口',
            prop: 'parentName',
            minWidth: 120,
            slot: true,
            addDisplay: false,
            editDisplay: false,
          },
          {
            label: '上级港口编码',
            prop: 'parentCode',
            minWidth: 120,
            slot: true,
            disabled: true,
          },
          {
            label: '城市',
            prop: 'regionCode',
            formslot: true,
            hide: true,
            span: 12,
            rules: [{ required: true, message: '请选择所属城市', trigger: 'change' }],
          },
          {
            label: '国家',
            prop: 'country',
            search: true,
            addDisplay: false,
            editDisplay: false,
            minWidth: 100,
          },
          {
            label: '城市',
            prop: 'city',
            search: true,
            addDisplay: false,
            editDisplay: false,
            minWidth: 100,
          },
          {
            label: '经度',
            prop: 'longitude',
            type: 'number',
            precision: 6,
            minWidth: 130,
            rules: [{ validator: validateLongitude, trigger: 'blur' }],
          },
          {
            label: '纬度',
            prop: 'latitude',
            type: 'number',
            precision: 6,
            minWidth: 130,
            rules: [{ validator: validateLatitude, trigger: 'blur' }],
          },
          {
            label: '数据来源',
            prop: 'dataSource',
            type: 'select',
            search: true,
            dicData: [
              { label: '全部', value: '' },
              { label: '初始化导入', value: '初始化导入' },
              { label: '批量导入', value: '批量导入' },
              { label: '手工导入', value: '手工导入' },
            ],
          },
          {
            label: '启停状态',
            prop: 'status',
            type: 'select',
            search: true,
            slot: true,
            dataType: 'number',
            dicData: [
              { label: '全部', value: '' },
              { label: '启用', value: 1 },
              { label: '停用', value: 2 },
            ],
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            minRows: 4,
            span: 24,
            hide: true,
            maxlength: 200,
            showWordLimit: true,
            rules: [{ max: 200, message: '备注不能超过200个字', trigger: 'blur' }],
          },
          {
            label: '更新人',
            prop: 'updateUserName',
            formatter: formatUpdateUserName,
            addDisplay: false,
            editDisplay: false,
            minWidth: 120,
          },
          {
            label: '更新时间',
            prop: 'updateTime',
            type: 'datetime',
            format: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            addDisplay: false,
            editDisplay: false,
            minWidth: 160,
          },
          {
            label: '创建时间',
            prop: 'createTime',
            type: 'datetime',
            format: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            addDisplay: false,
            editDisplay: false,
            display: false,
            minWidth: 160,
          },
        ],
      },
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '模板上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '模板上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data',
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            accept: '.xls,.xlsx',
            action: '/blade-system/port-terminal/import-port-terminal',
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(['permission', 'userInfo']),
    permissionList() {
      return {
        addBtn: this.hasPermission('port_terminal_add'),
      };
    },
    isAdmin() {
      const authority = this.userInfo && this.userInfo.authority;
      return Array.isArray(authority) ? authority.includes('admin') : String(authority || '').includes('admin');
    },
    isParentRegionLocked() {
      return this.form.category === '码头' && !!this.form.parentId;
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  created() {
    this.loadPortOptions();
  },
  methods: {
    hasPermission(code) {
      return this.isAdmin || this.validData(this.permission && this.permission[code], false);
    },
    handleCodeChange(value) {
      const code = String(value || '').toUpperCase();
      if (this.form.category === '港口') {
        this.form.code = code.replace(/[^A-Z]/g, '').slice(0, 5);
        return;
      }
      if (this.form.category === '码头') {
        this.form.code = code.replace(/[^A-Z0-9-]/g, '');
      }
    },
    loadRegionNode(node, resolve) {
      const parentCode = node.level === 0 ? '00' : node.value;
      getLazyTree(parentCode).then(res => {
        const regionList = res.data.data || [];
        const nodes = regionList.map(region => {
          this.regionNodeMap[region.id] = region;
          this.regionNameMap[region.title] = region.id;
          return {
            id: region.id,
            title: region.title,
            leaf: node.level >= 1,
          };
        });
        resolve(nodes);
      });
    },
    loadPortOptions() {
      getPortSelect().then(res => {
        this.portOptions = res.data.data;
        this.findColumn(this.option.column, 'parentId').dicData = this.portOptions;
      });
    },
    handleCategoryChange(value) {
      const parentColumn = this.findColumn(this.option.column, 'parentId');
      parentColumn.rules[0].required = value === '码头';
      if (value === '港口') {
        this.form.parentId = undefined;
        this.form.parentCode = '';
        this.form.parentName = '';
      }
      this.handleCodeChange(this.form.code);
    },
    handleParentChange(value) {
      const parent = this.portOptions.find(item => item.id === value);
      if (!parent) return;
      const terminalCode = String(this.form.code || '')
        .split('-')
        .slice(1)
        .join('-');
      this.form.parentCode = parent.code;
      this.form.parentName = parent.name;
      if (this.form.category === '码头' && terminalCode) {
        this.form.code = `${parent.code}-${terminalCode}`;
      }
      this.form.country = parent.country;
      this.form.city = parent.city;
      this.resolveRegionCode(parent.country, parent.city).then(regionCode => {
        this.form.regionCode = regionCode;
      });
    },
    handleRegionChange(value) {
      const regionCode = Array.isArray(value) ? value : [];
      const provinceCode = regionCode[0];
      const cityCode = regionCode[1];
      const province = this.regionNodeMap[provinceCode];
      const city = this.regionNodeMap[cityCode];
      this.form.country = province ? province.title : '';
      this.form.city = city ? city.title : '';
    },
    resolveRegionCode(country, city) {
      if (!country || !city) {
        return Promise.resolve([]);
      }
      const provinceCode = this.regionNameMap[country];
      if (provinceCode) {
        const cityCode = this.regionNameMap[city];
        if (cityCode) {
          return Promise.resolve([provinceCode, cityCode]);
        }
        return this.loadRegionList(provinceCode).then(cityList => {
          const cityNode = cityList.find(item => item.title === city);
          return cityNode ? [provinceCode, cityNode.id] : [provinceCode];
        });
      }
      return this.loadRegionList('00').then(provinceList => {
        const province = provinceList.find(item => item.title === country);
        if (!province) {
          return [];
        }
        return this.loadRegionList(province.id).then(cityList => {
          const cityNode = cityList.find(item => item.title === city);
          return cityNode ? [province.id, cityNode.id] : [province.id];
        });
      });
    },
    loadRegionList(parentCode) {
      return getLazyTree(parentCode).then(res => {
        const regionList = res.data.data || [];
        regionList.forEach(region => {
          this.regionNodeMap[region.id] = region;
          this.regionNameMap[region.title] = region.id;
        });
        return regionList;
      });
    },
    normalizeRow(row) {
      row.code = String(row.code || '').toUpperCase();
      if (row.category === '港口') {
        row.parentId = undefined;
        row.parentCode = undefined;
        row.parentName = undefined;
      }
      if (!row.dataSource) row.dataSource = '手工导入';
      if (!row.status) row.status = 1;
      return row;
    },
    validateRequiredFields(row) {
      const isBlank = value => value === undefined || value === null || String(value).trim() === '';
      if (isBlank(row.code)) {
        this.$message.warning('请输入编码');
        return false;
      }
      if (isBlank(row.name)) {
        this.$message.warning('请输入港口/码头名称');
        return false;
      }
      if (isBlank(row.category)) {
        this.$message.warning('请选择类型');
        return false;
      }
      if (row.category === '码头' && isBlank(row.parentId)) {
        this.$message.warning('请选择上级港口');
        return false;
      }
      if (!Array.isArray(row.regionCode) || row.regionCode.length < 2) {
        this.$message.warning('请选择所属城市');
        return false;
      }
      return true;
    },
    stopSubmitLoading(loading) {
      if (typeof loading === 'function') {
        loading();
      }
    },
    rowSave(row, done, loading) {
      const submitRow = this.normalizeRow(row);
      if (!this.validateRequiredFields(submitRow)) {
        this.stopSubmitLoading(loading);
        return;
      }
      submit(submitRow).then(
        () => {
          this.onLoad(this.page);
          this.loadPortOptions();
          this.$message({ type: 'success', message: '操作成功!' });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      const submitRow = this.normalizeRow(row);
      if (!this.validateRequiredFields(submitRow)) {
        this.stopSubmitLoading(loading);
        return;
      }
      submit(submitRow).then(
        () => {
          this.onLoad(this.page);
          this.loadPortOptions();
          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.loadPortOptions();
          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.loadPortOptions();
          this.$message({ type: 'success', message: '操作成功!' });
          this.$refs.crud.toggleSelection();
        });
    },
    handleStatus(row) {
      const nextStatus = row.status === 1 ? 2 : 1;
      const actionName = nextStatus === 1 ? '启用' : '停用';
      this.$confirm(`是否确认${actionName}该条数据？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => changeStatus(row.id, nextStatus))
        .then(() => {
          this.onLoad(this.page);
          this.loadPortOptions();
          this.$message({ type: 'success', message: '操作成功!' });
        });
    },
    beforeOpen(done, type) {
      if (type === 'add') {
        this.form.category = this.form.category || '港口';
        this.form.dataSource = this.form.dataSource || '手工导入';
        this.form.status = this.form.status || 1;
      }
      this.handleCategoryChange(this.form.category || '港口');
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          this.resolveRegionCode(this.form.country, this.form.city).then(regionCode => {
            this.form.regionCode = regionCode;
            this.handleCategoryChange(this.form.category);
            done();
          });
        });
        return;
      } else {
        this.resolveRegionCode(this.form.country, this.form.city).then(regionCode => {
          this.form.regionCode = regionCode;
          done();
        });
        return;
      }
    },
    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() {
      this.excelBox = true;
    },
    uploadBefore(file, done) {
      const fileName = file && file.name ? file.name.toLowerCase() : '';
      if (!/\.(xls|xlsx)$/.test(fileName)) {
        this.$message.error('请上传 .xls,.xlsx 标准格式文件');
        return false;
      }
      if (typeof done === 'function') {
        done();
      }
      return true;
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.onLoad(this.page);
      this.loadPortOptions();
      done();
    },
    handleExport() {
      this.$confirm('是否导出港口码头主数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        NProgress.start();
        exportBlob('/blade-system/port-terminal/export-port-terminal', this.buildExportParams())
          .then(res => {
            downloadXls(
              res.data,
              `港口码头主数据${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-system/port-terminal/export-template?${this.website.tokenHeader}=${getToken()}`
      ).then(res => {
        downloadXls(res.data, '港口码头主数据模板.xlsx');
      });
    },
  },
};
</script>

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