<template>
  <basic-container class="railway-station-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('railway_station_import')"
          @click="handleImport"
          >批量导入
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          plain
          v-if="hasPermission('railway_station_template')"
          @click="handleTemplate"
          >下载模板
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          plain
          v-if="hasPermission('railway_station_export')"
          @click="handleExport"
          >批量导出
        </el-button>
        <el-button
          type="danger"
          icon="el-icon-delete"
          plain
          v-if="hasPermission('railway_station_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-link
          type="primary"
          v-if="hasPermission('railway_station_edit')"
          @click="$refs.crud.rowEdit(row, index)"
        >
          编辑
        </el-link>
        <el-link
          type="primary"
          v-if="hasPermission('railway_station_status')"
          @click="handleStatus(row)"
        >
          {{ row.status === 1 ? '停用' : '启用' }}
        </el-link>
      </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/railway-station';
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 validateTmisCode = (rule, value, callback) => {
      if (!/^\d{5}$/.test(value || '')) {
        callback(new Error('TMIS国标编码为5位数字'));
      } else {
        callback();
      }
    };
    const validateTelegraphCode = (rule, value, callback) => {
      if (!/^[A-Z]{3}$/.test(String(value || '').toUpperCase())) {
        callback(new Error('电报码格式不正确或已存在'));
      } else {
        callback();
      }
    };
    const validateStationName = (rule, value, callback) => {
      const name = String(value || '').trim();
      if (!name || name.length > 50) {
        callback(new Error('请输入车站名称'));
      } else {
        callback();
      }
    };
    const validateLongitude = (rule, value, callback) => {
      const message = getCoordinateValidationMessage(value, 'longitude');
      if (message) {
        callback(new Error('经度范围不正确'));
      } else {
        callback();
      }
    };
    const validateLatitude = (rule, value, callback) => {
      const message = getCoordinateValidationMessage(value, 'latitude');
      if (message) {
        callback(new Error('纬度范围不正确'));
      } 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',
        labelWidth: 'auto',
        tip: false,
        searchShow: true,
        searchMenuSpan: 24,
        searchIcon: true,
        searchIndex: 4,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        indexLabel: '序号',
        indexWidth: 70,
        viewBtn: false,
        delBtn: false,
        editBtn: false,
        selection: true,
        dialogClickModal: false,
        menuWidth: 180,
        column: [
          {
            label: '编码',
            prop: 'code',
            minWidth: 120,
            overHidden: false,
            search: true,
            addDisplay: false,
            editDisplay: false,
            placeholder: '系统自动生成',
            searchPlaceholder: '请输入编码',
          },
          {
            label: 'TMIS国标编码',
            prop: 'tmisCode',
            minWidth: 120,
            maxlength: 5,
            rules: [
              { required: true, message: '请输入TMIS国标编码', trigger: 'blur' },
              { validator: validateTmisCode, trigger: 'blur' },
            ],
            change: ({ value }) => this.handleTmisChange(value),
          },
          {
            label: '电报码',
            prop: 'telegraphCode',
            minWidth: 100,
            maxlength: 3,
            rules: [
              { required: true, message: '电报码格式不正确或已存在', trigger: 'blur' },
              { validator: validateTelegraphCode, trigger: 'blur' },
            ],
            change: ({ value }) => this.handleTelegraphChange(value),
            blur: ({ value }) => this.handleTelegraphChange(value),
          },
          {
            label: '车站名称',
            prop: 'name',
            minWidth: 120,
            maxlength: 50,
            search: true,
            rules: [{ validator: validateStationName, trigger: 'blur' }],
          },
          // {
          //   label: '所属铁路线路',
          //   prop: 'railwayLine',
          //   minWidth: 130,
          // },
          {
            label: '所属省份',
            prop: 'provinceCode',
            type: 'select',
            hide: true,
            props: {
              label: 'title',
              value: 'id',
            },
            dicData: [],
            filterable: true,
            span: 12,
            rules: [{ required: true, message: '请选择所属省份', trigger: 'change' }],
            change: ({ value }) => this.handleProvinceChange(value),
          },
          {
            label: '所属城市',
            prop: 'cityCode',
            type: 'select',
            hide: true,
            props: {
              label: 'title',
              value: 'id',
            },
            dicData: [],
            filterable: true,
            span: 12,
            rules: [{ required: true, message: '请选择所属城市', trigger: 'change' }],
            change: ({ value }) => this.handleCityChange(value),
          },
          {
            label: '所属省份',
            prop: 'provinceName',
            minWidth: 140,
            addDisplay: false,
            editDisplay: false,
          },
          {
            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,
            span: 12,
            rules: [{ required: true, message: '请选择所属区县', trigger: 'change' }],
            change: ({ value }) => this.handleDistrictChange(value),
          },
          {
            label: '所属区县',
            prop: 'districtName',
            minWidth: 140,
            addDisplay: false,
            editDisplay: false,
          },
          {
            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: [{ validator: validateLongitude, trigger: 'blur' }],
          },
          {
            label: '纬度',
            prop: 'latitude',
            formslot: true,
            minWidth: 130,
            overHidden: false,
            rules: [{ validator: validateLatitude, trigger: 'blur' }],
          },
          {
            label: '行政区划编号',
            prop: 'regionCode',
            minWidth: 160,
            overHidden: false,
            addDisplay: false,
            editDisplay: false,
            rules: [{ max: 32, message: '行政区划编码不能超过32字', trigger: 'blur' }],
          },
          {
            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',
            sortable: true,
            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',
            sortable: true,
            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: 'dataSource',
            type: 'select',
            search: true,
            minWidth: 120,
            overHidden: false,
            addDisplay: false,
            editDisplay: false,
            dicData: [
              { label: '全部', value: '' },
              { label: '初始化导入', value: '初始化导入' },
              { label: '批量', value: '批量' },
              { label: '手动', value: '手动' },
            ],
          },
        ],
      },
      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/railway-station/import-railway-station',
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(['permission', 'userInfo']),
    permissionList() {
      return {
        addBtn: this.hasPermission('railway_station_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(columns, prop) {
      const targetColumns = Array.isArray(columns) ? columns : this.option.column;
      const targetProp = Array.isArray(columns) ? prop : columns;
      return targetColumns.find(item => item.prop === targetProp) || null;
    },
    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),
      };
    },
    ensureCityOption(row) {
      if (!row.cityCode || !row.cityName) return;
      const exists = this.cityOptions.some(item => item.id === row.cityCode);
      if (exists) return;
      this.cityOptions = [
        ...this.cityOptions,
        {
          id: row.cityCode,
          title: row.cityName,
        },
      ];
      this.findColumn('cityCode').dicData = this.cityOptions;
    },
    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;
    },
    handleTmisChange(value) {
      this.form.tmisCode = String(value || '')
        .replace(/\D/g, '')
        .slice(0, 5);
      this.form.code = this.form.tmisCode ? `TL${this.form.tmisCode}` : '';
    },
    handleTelegraphChange(value) {
      this.form.telegraphCode = String(value || '')
        .toUpperCase()
        .replace(/[^A-Z]/g, '')
        .slice(0, 3);
    },
    handleProvinceChange(value) {
      const province = this.provinceOptions.find(item => item.id === value);
      this.form.provinceName = province ? province.title : '';
      if (this.regionInitializing) {
        this.loadCityOptions(value).then(() => this.ensureCityOption(this.form));
        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).then(() => this.ensureDistrictOption(this.form));
        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.tmisCode ? `TL${row.tmisCode}` : 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');
      if (longitudeMessage) {
        this.$message.warning('经度范围不正确');
        return false;
      }
      const latitudeMessage = getCoordinateValidationMessage(row.latitude, 'latitude');
      if (latitudeMessage) {
        this.$message.warning('纬度范围不正确');
        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({ tmisCode: row.tmisCode }, 'tmisCode'),
        hasDuplicate({ telegraphCode: row.telegraphCode }, 'telegraphCode'),
      ]).then(([tmisExists, telegraphExists]) => {
        if (tmisExists) {
          return Promise.reject(new Error('该TMIS编码已存在'));
        }
        if (telegraphExists) {
          return Promise.reject(new Error('电报码格式不正确或已存在'));
        }
        return Promise.resolve();
      });
    },
    handleSubmitError(error, loading) {
      const uniqueMessages = ['该TMIS编码已存在', '电报码格式不正确或已存在'];
      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.ensureCityOption(detail);
              return 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/railway-station/export-railway-station',
          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.query,
        ids: this.ids,
        [this.website.tokenHeader]: getToken(),
      };
    },
    handleTemplate() {
      exportBlob(
        `/blade-system/railway-station/export-template?${this.website.tokenHeader}=${getToken()}`,
        undefined,
        { feedback: true }
      ).then(res => {
        downloadXls(res.data, '铁路车站主数据模板.xlsx');
      });
    },
  },
};
</script>

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