<template>
  <basic-container class="airport-master-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('airport_master_import')"
          @click="handleImport"
          >批量导入
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          plain
          v-if="hasPermission('airport_master_template')"
          @click="handleTemplate"
          >下载模板
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          plain
          v-if="hasPermission('airport_master_export')"
          @click="handleExport"
          >批量导出
        </el-button>
        <el-button
          type="danger"
          icon="el-icon-delete"
          plain
          v-if="hasPermission('airport_master_delete')"
          @click="handleDelete"
          >批量删除
        </el-button>
      </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('airport_master_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('airport_master_status')"
          @click="handleStatus(row)"
        >
          {{ row.status === 1 ? '停用' : '启用' }}
        </el-button>
      </template>
      <template #districtCode-form>
        <el-select
          v-model="form.districtCode"
          clearable
          filterable
          :loading="districtLoading"
          :disabled="!form.cityCode"
          :placeholder="form.cityCode ? '请选择区县' : '请先选择城市'"
          style="width: 100%"
          @change="handleDistrictChange"
        >
          <el-option
            v-for="item in districtOptions"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </template>
      <template #longitude-form>
        <el-input
          v-model="form.longitude"
          clearable
          placeholder="请输入经度"
          @input="handleCoordinateInput('longitude', $event)"
        />
      </template>
      <template #latitude-form>
        <el-input
          v-model="form.latitude"
          clearable
          placeholder="请输入纬度"
          @input="handleCoordinateInput('latitude', $event)"
        />
      </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, submit, remove, changeStatus } from '@/api/base/airport-master';
import { getLazyTree } from '@/api/base/region';
import { exportBlob } from '@/api/common';
import { mapGetters } from 'vuex';
import { downloadXls } from '@/utils/util';
import { openImportDialog } from '@/utils/import-excel';
import { formatUpdateUserName } from '@/utils/audit';
import { getToken } from '@/utils/auth';
import { getCoordinateValidationMessage, normalizeCoordinateInput } from '@/utils/coordinate';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

const DEFAULT_COUNTRY_CODE = '+86';

export default {
  data() {
    const validateIataCode = (rule, value, callback) => {
      if (!/^[A-Z]{3}$/.test(String(value || '').toUpperCase())) {
        callback(new Error('IATA编码为3位大写字母'));
      } else {
        callback();
      }
    };
    const validateIcaoCode = (rule, value, callback) => {
      if (!/^[A-Z]{4}$/.test(String(value || '').toUpperCase())) {
        callback(new Error('ICAO代码为4位大写字母'));
      } else {
        callback();
      }
    };
    const validateLongitude = (rule, value, callback) => {
      const message = getCoordinateValidationMessage(value, 'longitude');
      if (message) {
        callback(new Error(message));
      } else {
        callback();
      }
    };
    const validateLatitude = (rule, value, callback) => {
      const message = getCoordinateValidationMessage(value, 'latitude');
      if (message) {
        callback(new Error(message));
      } else {
        callback();
      }
    };
    return {
      form: {},
      query: {},
      loading: true,
      data: [],
      excelBox: false,
      excelForm: {},
      provinceOptions: [],
      cityOptions: [],
      districtOptions: [],
      districtLoading: false,
      regionInitializing: false,
      page: {
        pageSize: 10,
        pageSizes: [10, 20, 50, 100],
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 32,
        dialogWidth: 980,
        labelPosition: 'right',
        tip: false,
        searchShow: true,
        labelWidth: 'auto',
        searchLabelWidth: 160,
        searchMenuSpan: 24,
        searchIcon: true,
        searchIndex: 8,
        searchMenuPosition: 'right',
        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,
            addDisplay: false,
            editDisplay: false,
            placeholder: '系统自动生成',
            searchPlaceholder: '请输入编码',
          },
          {
            label: 'IATA编码',
            prop: 'iataCode',
            minWidth: 120,
            maxlength: 3,
            rules: [
              { required: true, message: '请输入IATA编码', trigger: 'blur' },
              { validator: validateIataCode, trigger: 'blur' },
            ],
            change: ({ value }) => this.handleIataChange(value),
            blur: ({ value }) => this.handleIataChange(value),
          },
          {
            label: 'ICAO代码',
            prop: 'icaoCode',
            minWidth: 100,
            maxlength: 4,
            rules: [
              { required: true, message: '请输入ICAO代码', trigger: 'blur' },
              { validator: validateIcaoCode, trigger: 'blur' },
            ],
            change: ({ value }) => this.handleIcaoChange(value),
            blur: ({ value }) => this.handleIcaoChange(value),
          },
          {
            label: '机场标准名称',
            prop: 'name',
            minWidth: 180,
            search: true,
            rules: [{ required: true, message: '请输入机场标准名称', trigger: 'blur' }],
          },
          {
            label: '机场简称',
            prop: 'shortName',
            minWidth: 130,
          },
          {
            label: '所属省份',
            prop: 'provinceCode',
            type: 'select',
            minWidth: 120,
            hide: true,
            props: {
              label: 'title',
              value: 'id',
            },
            dicData: [],
            filterable: true,
            rules: [{ required: true, message: '请选择省份', trigger: 'change' }],
            change: ({ value }) => this.handleProvinceChange(value),
          },
          {
            label: '所属省份',
            prop: 'provinceName',
            minWidth: 140,
            addDisplay: false,
            editDisplay: false,
          },
          {
            label: '所属城市',
            prop: 'cityCode',
            type: 'select',
            minWidth: 120,
            hide: true,
            props: {
              label: 'title',
              value: 'id',
            },
            dicData: [],
            filterable: true,
            rules: [{ required: true, message: '请选择城市', trigger: 'change' }],
            change: ({ value }) => this.handleCityChange(value),
          },
          {
            label: '所属城市',
            prop: 'cityName',
            minWidth: 140,
            addDisplay: false,
            editDisplay: false,
          },
          {
            label: '所属区县',
            prop: 'districtCode',
            type: 'select',
            formslot: true,
            hide: true,
            props: {
              label: 'title',
              value: 'id',
            },
            dicData: [],
            filterable: true,
            rules: [{ required: true, message: '请选择区县', trigger: 'change' }],
            change: ({ value }) => this.handleDistrictChange(value),
          },
          {
            label: '所属区县',
            prop: 'districtName',
            minWidth: 140,
            addDisplay: false,
            editDisplay: false,
          },
          {
            label: '行政区划编号',
            prop: 'regionCode',
            minWidth: 160,
            overHidden: false,
            addDisplay: false,
            editDisplay: false,
            rules: [{ max: 32, message: '行政区划编码不能超过32字', trigger: 'blur' }],
          },
          {
            label: '详细地址',
            prop: 'detailAddress',
            type: 'textarea',
            minRows: 3,
            span: 24,
            minWidth: 220,
            overHidden: false,
            maxlength: 255,
            showWordLimit: true,
            rules: [{ max: 255, message: '详细地址不能超过255字', trigger: 'blur' }],
          },
          {
            label: '经度',
            prop: 'longitude',
            formslot: true,
            minWidth: 130,
            overHidden: false,
            rules: [
              { required: true, message: '请输入经度', trigger: 'blur' },
              { validator: validateLongitude, trigger: 'blur' },
            ],
          },
          {
            label: '纬度',
            prop: 'latitude',
            formslot: true,
            minWidth: 130,
            overHidden: false,
            rules: [
              { required: true, message: '请输入纬度', trigger: 'blur' },
              { validator: validateLatitude, trigger: 'blur' },
            ],
          },
          {
            label: '数据来源',
            prop: 'dataSource',
            type: 'select',
            search: true,
            minWidth: 120,
            overHidden: false,
            addDisplay: false,
            editDisplay: false,
            dicData: [
              { label: '全部', value: '' },
              { label: '初始导入', value: '初始导入' },
              { label: '批量导入', value: '批量导入' },
              { label: '手动录入', value: '手动录入' },
            ],
          },
          {
            label: '启停状态',
            prop: 'status',
            type: 'select',
            search: true,
            slot: true,
            dataType: 'number',
            minWidth: 110,
            overHidden: false,
            addDisplay: false,
            editDisplay: false,
            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,
            display: 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: {
        labelPosition: 'right',
        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/airport-master/import-airport-master',
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(['permission', 'userInfo']),
    permissionList() {
      return {
        addBtn: this.hasPermission('airport_master_add'),
      };
    },
    isAdmin() {
      const authority = this.userInfo && this.userInfo.authority;
      return Array.isArray(authority)
        ? authority.includes('admin')
        : String(authority || '').includes('admin');
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  created() {
    this.loadProvinceOptions();
  },
  methods: {
    hasPermission(code) {
      return this.isAdmin || this.validData(this.permission && this.permission[code], false);
    },
    findColumn(prop) {
      return this.option.column.find(item => item.prop === prop);
    },
    loadProvinceOptions() {
      getLazyTree(DEFAULT_COUNTRY_CODE).then(res => {
        this.provinceOptions = (res.data.data || []).map(this.normalizeRegionOption);
        this.findColumn('provinceCode').dicData = this.provinceOptions;
      });
    },
    loadCityOptions(provinceCode) {
      if (!provinceCode) {
        this.cityOptions = [];
        this.findColumn('cityCode').dicData = [];
        return Promise.resolve();
      }
      return getLazyTree(provinceCode).then(res => {
        this.cityOptions = (res.data.data || []).map(this.normalizeRegionOption);
        this.findColumn('cityCode').dicData = this.cityOptions;
      });
    },
    loadDistrictOptions(cityCode) {
      if (!cityCode) {
        this.districtOptions = [];
        this.findColumn('districtCode').dicData = [];
        return Promise.resolve();
      }
      this.districtLoading = true;
      return getLazyTree(cityCode)
        .then(res => {
          this.districtOptions = (res.data.data || []).map(this.normalizeRegionOption);
          this.findColumn('districtCode').dicData = this.districtOptions;
        })
        .finally(() => {
          this.districtLoading = false;
        });
    },
    normalizeRegionOption(region) {
      return {
        ...region,
        id: region.id === undefined || region.id === null ? region.id : String(region.id),
      };
    },
    normalizeRegionForm(row) {
      return {
        ...row,
        provinceCode:
          row.provinceCode === undefined || row.provinceCode === null
            ? row.provinceCode
            : String(row.provinceCode),
        cityCode:
          row.cityCode === undefined || row.cityCode === null ? row.cityCode : String(row.cityCode),
        districtCode:
          row.districtCode === undefined || row.districtCode === null
            ? row.districtCode
            : String(row.districtCode),
      };
    },
    ensureDistrictOption(row) {
      if (!row.districtCode || !row.districtName) return;
      const exists = this.districtOptions.some(item => item.id === row.districtCode);
      if (exists) return;
      this.districtOptions = [
        ...this.districtOptions,
        {
          id: row.districtCode,
          title: row.districtName,
        },
      ];
      this.findColumn('districtCode').dicData = this.districtOptions;
    },
    handleIataChange(value) {
      this.form.iataCode = String(value || '')
        .toUpperCase()
        .replace(/[^A-Z]/g, '')
        .slice(0, 3);
      this.form.code = this.form.iataCode ? `JC-${this.form.iataCode}` : '';
    },
    handleIcaoChange(value) {
      this.form.icaoCode = String(value || '')
        .toUpperCase()
        .replace(/[^A-Z]/g, '')
        .slice(0, 4);
    },
    handleProvinceChange(value) {
      const province = this.provinceOptions.find(item => item.id === value);
      this.form.provinceName = province ? province.title : '';
      if (this.regionInitializing) {
        this.loadCityOptions(value);
        return;
      }
      this.form.cityCode = undefined;
      this.form.cityName = '';
      this.form.districtCode = undefined;
      this.form.districtName = '';
      this.form.regionCode = '';
      this.form.regionName = '';
      this.loadCityOptions(value);
      this.loadDistrictOptions();
    },
    handleCityChange(value) {
      const city = this.cityOptions.find(item => item.id === value);
      this.form.cityName = city ? city.title : '';
      if (this.regionInitializing) {
        this.loadDistrictOptions(value);
        return;
      }
      this.form.districtCode = undefined;
      this.form.districtName = '';
      this.form.regionCode = '';
      this.form.regionName = '';
      this.loadDistrictOptions(value);
    },
    handleDistrictChange(value) {
      const district = this.districtOptions.find(item => item.id === value);
      this.form.districtName = district ? district.title : '';
      this.form.regionCode = value || '';
      this.form.regionName = district ? district.title : '';
    },
    handleCoordinateInput(prop, value) {
      this.form[prop] = normalizeCoordinateInput(value);
    },
    normalizeRow(row) {
      row.code = row.iataCode ? `JC-${row.iataCode}` : row.code;
      row.regionCode = String(row.regionCode || '').trim();
      row.regionName = String(row.regionName || '').trim();
      row.districtCode = String(row.districtCode || '').trim();
      row.districtName = String(row.districtName || '').trim();
      row.detailAddress = String(row.detailAddress || '').trim();
      row.longitude = normalizeCoordinateInput(row.longitude);
      row.latitude = normalizeCoordinateInput(row.latitude);
      if (!row.dataSource) row.dataSource = '手动录入';
      if (!row.status) row.status = 1;
      return row;
    },
    validateCoordinateFields(row) {
      const longitudeMessage = getCoordinateValidationMessage(row.longitude, 'longitude', true);
      if (longitudeMessage) {
        this.$message.warning(longitudeMessage);
        return false;
      }
      const latitudeMessage = getCoordinateValidationMessage(row.latitude, 'latitude', true);
      if (latitudeMessage) {
        this.$message.warning(latitudeMessage);
        return false;
      }
      return true;
    },
    validateUnique(row) {
      const rowId = String(row.id || '');
      const hasDuplicate = (params, prop) => {
        return getList(1, 10, params).then(res => {
          const records = res.data.data.records || [];
          return records.some(item => item[prop] === row[prop] && String(item.id || '') !== rowId);
        });
      };
      return Promise.all([
        hasDuplicate({ iataCode: row.iataCode }, 'iataCode'),
        hasDuplicate({ icaoCode: row.icaoCode }, 'icaoCode'),
      ]).then(([iataExists, icaoExists]) => {
        if (iataExists) {
          return Promise.reject(new Error('该IATA编码已存在'));
        }
        if (icaoExists) {
          return Promise.reject(new Error('该ICAO代码已存在'));
        }
        return Promise.resolve();
      });
    },
    handleSubmitError(error, loading) {
      const uniqueMessages = ['该IATA编码已存在', '该ICAO代码已存在'];
      if (uniqueMessages.includes(error.message)) {
        this.$message.warning(error.message);
      }
      window.console.log(error);
      loading();
    },
    rowSave(row, done, loading) {
      const submitRow = this.normalizeRow(row);
      if (!this.validateCoordinateFields(submitRow)) {
        loading();
        return;
      }
      this.validateUnique(submitRow)
        .then(() => submit(submitRow))
        .then(() => {
          this.onLoad(this.page);
          this.$message({ type: 'success', message: '操作成功!' });
          done();
        })
        .catch(error => this.handleSubmitError(error, loading));
    },
    rowUpdate(row, index, done, loading) {
      const submitRow = this.normalizeRow(row);
      if (!this.validateCoordinateFields(submitRow)) {
        loading();
        return;
      }
      this.validateUnique(submitRow)
        .then(() => submit(submitRow))
        .then(() => {
          this.onLoad(this.page);
          this.$message({ type: 'success', message: '操作成功!' });
          done();
        })
        .catch(error => this.handleSubmitError(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();
        });
    },
    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.$message({ type: 'success', message: '操作成功!' });
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        this.regionInitializing = true;
        getDetail(this.form.id).then(res => {
          const detail = this.normalizeRegionForm(res.data.data || {});
          this.loadCityOptions(detail.provinceCode)
            .then(() => this.loadDistrictOptions(detail.cityCode))
            .then(() => {
              this.ensureDistrictOption(detail);
              this.form = detail;
              done();
              this.$nextTick(() => {
                window.setTimeout(() => {
                  this.regionInitializing = false;
                }, 0);
              });
            });
        });
        return;
      }
      this.form.code = '';
      this.form.dataSource = '手动录入';
      this.form.status = 1;
      this.loadCityOptions(this.form.provinceCode)
        .then(() => this.loadDistrictOptions(this.form.cityCode))
        .then(() => 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, '空港机场主数据');
    },
    handleExport() {
      this.$confirm('是否导出空港机场主数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        NProgress.start();
        exportBlob('/blade-system/airport-master/export-airport-master', 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/airport-master/export-template?${this.website.tokenHeader}=${getToken()}`
      ).then(res => {
        downloadXls(res.data, '空港机场主数据模板.xlsx');
      });
    },
  },
};
</script>

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