<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      ref="crud"
      v-model="form"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      @row-del="rowDel"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      @tree-load="treeLoad"
    >
      <template #menu-left>
        <el-button
          type="danger"
          icon="el-icon-delete"
          v-if="permission.dept_delete"
          plain
          @click="handleDelete"
          >删除
        </el-button>
      </template>
      <template #menu="scope">
        <el-link
          type="primary"
          @click.stop="handleAdd(scope.row, scope.index)"
          v-if="userInfo.authority.includes('admin')"
          >新增子项
        </el-link>
      </template>
      <template #deptCategory="{ row }">
        <el-tag>{{ getDeptCategoryLabel(row.deptCategory) }}</el-tag>
      </template>
      <template #leaderId="{ row }">
        {{ getLeaderValue(row.leaderId, 'realName') }}
      </template>
      <template #leaderPhone="{ row }">
        {{ getLeaderValue(row.leaderId, 'phone') }}
      </template>
      <template #status="{ row }">
        <el-tag :type="Number(row.status) === 1 ? 'success' : 'info'">
          {{ Number(row.status) === 1 ? '启用' : '停用' }}
        </el-tag>
      </template>
    </avue-crud>
    <el-dialog v-model="carrierDialogVisible" title="选择承运商" width="1100px" append-to-body>
      <el-form :inline="true" :model="carrierQuery" class="carrier-search-form">
        <el-form-item label="名称">
          <el-input v-model="carrierQuery.fullName" placeholder="请输入承运商名称" clearable />
        </el-form-item>
        <el-form-item label="准入标准">
          <el-select v-model="carrierQuery.accessType" placeholder="全部" clearable>
            <el-option label="临时" value="temporary" />
            <el-option label="正式" value="formal" />
          </el-select>
        </el-form-item>
        <el-form-item label="审批状态">
          <el-select v-model="carrierQuery.approvalStatus" placeholder="全部" clearable>
            <el-option label="草稿" value="draft" />
            <el-option label="审核中" value="reviewing" />
            <el-option label="审核通过" value="approved" />
            <el-option label="审核不通过" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="carrierQuery.status" placeholder="全部" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="停用" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchCarrier">搜索</el-button>
          <el-button @click="resetCarrierQuery">清空</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="carrierData" border stripe height="420" @row-dblclick="selectCarrier">
        <el-table-column prop="customerCode" label="客商编号" min-width="130" />
        <el-table-column prop="shortName" label="客商简称" min-width="140" />
        <el-table-column prop="fullName" label="客商名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="customerType" label="客户类型" min-width="120" />
        <el-table-column prop="customerNature" label="客户性质" min-width="120" />
        <el-table-column prop="unifiedCreditCode" label="统一信用代码" min-width="180" />
        <el-table-column prop="deptName" label="所属组织" min-width="150" />
        <el-table-column prop="accessType" label="准入标准" min-width="110">
          <template #default="{ row }">{{ formatAccessType(row.accessType) }}</template>
        </el-table-column>
        <el-table-column prop="approvalStatus" label="审批状态" min-width="120">
          <template #default="{ row }">{{ formatApprovalStatus(row.approvalStatus) }}</template>
        </el-table-column>
        <el-table-column prop="currentNode" label="当前节点" min-width="130" />
        <el-table-column prop="currentProcessor" label="当前处理人" min-width="130" />
        <el-table-column prop="approvedTime" label="审核通过时间" min-width="170"  sortable/>
        <el-table-column prop="status" label="状态" width="90">
          <template #default="{ row }">{{ Number(row.status) === 1 ? '启用' : '停用' }}</template>
        </el-table-column>
        <el-table-column label="操作" width="90" fixed="right">
          <template #default="{ row }">
            <el-link type="primary" @click="selectCarrier(row)">选择</el-link>
          </template>
        </el-table-column>
      </el-table>
      <div class="carrier-pagination">
        <el-pagination
          v-model:current-page="carrierPage.current"
          v-model:page-size="carrierPage.size"
          :total="carrierPage.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          @current-change="loadCarrierList"
          @size-change="handleCarrierSizeChange"
        />
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getLazyList, remove, update, add, getDept, getDeptTree } from '@/api/system/dept';
import { getLeaderList } from '@/api/system/user';
import { getList as getCustomerArchiveList } from '@/api/vehicle/customer-archive';
import { mapGetters } from 'vuex';
import website from '@/config/website';
import func from '@/utils/func';

const escapeRegExp = value => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

export default {
  data() {
    return {
      form: {},
      leaderOptions: [],
      parentDeptCode: '',
      parentDept: null,
      carrierDialogVisible: false,
      carrierData: [],
      carrierQuery: {
        fullName: '',
        accessType: '',
        approvalStatus: '',
        status: undefined,
      },
      carrierPage: {
        current: 1,
        size: 10,
        total: 0,
      },
      selectionList: [],
      query: {},
      loading: true,
      parentId: 0,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option: {
        lazy: true,
        tip: false,
        simplePage: true,
        searchShow: true,
        searchMenuSpan: 24,
        searchIcon: true,
        searchIndex: 4,
        searchMenuPosition: 'right',
        tree: true,
        border: true,
        index: true,
        selection: true,
        viewBtn: true,
        menuWidth: 320,
        dialogWidth: 800,
        dialogClickModal: false,
        labelPosition: 'right',
        labelWidth: 'auto',
        column: [
          {
            label: '组织名称',
            prop: 'deptName',
            minWidth: 160,
            order: 80,
            search: true,
            rules: [
              {
                required: true,
                message: '请输入组织名称',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '组织编码',
            prop: 'deptCode',
            minWidth: 140,
            order: 70,
            maxlength: 30,
            showWordLimit: true,
            rules: [
              {
                required: true,
                message: '请输入组织编码',
                trigger: 'blur',
              },
              {
                validator: (rule, value, callback) => {
                  const deptCode = String(value || '').trim();
                  if (deptCode.length > 30) {
                    callback(new Error('组织编码不能超过30个字符'));
                    return;
                  }
                  if (!this.parentDeptCode) {
                    callback(new Error('请先选择上级组织'));
                    return;
                  }
                  const pattern = new RegExp(`^${escapeRegExp(this.parentDeptCode)}-\\d+$`);
                  if (!pattern.test(deptCode)) {
                    callback(new Error(`组织编码格式应为：${this.parentDeptCode}-分段数字`));
                    return;
                  }
                  callback();
                },
                trigger: 'blur',
              },
            ],
          },
          {
            label: '组织简称',
            prop: 'shortName',
            minWidth: 140,
            order: 60,
          },
          {
            label: '组织类型',
            type: 'select',
            dicData: [
              { label: '一级集团', value: 1 },
              { label: '二级事业部', value: 2 },
              { label: '部门', value: 3 },
              { label: '三级分公司', value: 4 },
              { label: '物流园区', value: 5 },
              { label: '承运商', value: 6 },
            ],
            dataType: 'number',
            minWidth: 120,
            order: 90,
            prop: 'deptCategory',
            slot: true,
            change: ({ value }) => this.handleDeptCategoryChange(value),
            rules: [
              {
                required: true,
                message: '请选择组织类型',
                trigger: 'change',
              },
            ],
          },
          {
            label: '负责人',
            prop: 'leaderId',
            minWidth: 120,
            slot: true,
            addDisplay: false,
            editDisplay: false,
          },
          {
            label: '联系电话',
            prop: 'leaderPhone',
            minWidth: 140,
            slot: true,
            addDisplay: false,
            editDisplay: false,
          },
          {
            label: '助记码',
            prop: 'mnemonicCode',
            minWidth: 120,
            order: 40,
          },
          {
            label: '拼音助记码',
            prop: 'pinyinMnemonic',
            minWidth: 140,
            order: 50,
          },
          {
            label: '排序',
            prop: 'sort',
            type: 'number',
            align: 'right',
            width: 80,
            order: 30,
            rules: [
              {
                required: true,
                message: '请输入排序',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '状态',
            prop: 'status',
            width: 100,
            slot: true,
            addDisplay: false,
            editDisplay: false,
          },
          {
            label: '上级组织',
            prop: 'parentId',
            dicData: [],
            type: 'tree',
            hide: true,
            addDisabled: false,
            order: 100,
            change: ({ value }) => this.handleParentChange(value),
            props: {
              label: 'title',
            },
            rules: [
              {
                required: true,
                message: '请选择上级组织',
                trigger: 'click',
              },
            ],
          },
          {
            label: '所属租户',
            prop: 'tenantId',
            type: 'tree',
            dicUrl: '/blade-system/tenant/select',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: website.tenantMode,
            props: {
              label: 'tenantName',
              value: 'tenantId',
            },
            hide: true,
            search: website.tenantMode,
          },
          {
            label: '机构全称',
            prop: 'fullName',
            search: true,
            hide: true,
            addDisplay: false,
            editDisplay: false,
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            hide: true,
            addDisplay: false,
            editDisplay: false,
          },
        ],
      },
      data: [],
    };
  },
  created() {
    this.loadLeaderOptions();
  },
  computed: {
    ...mapGetters(['userInfo', 'permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.dept_add, false),
        viewBtn: this.validData(this.permission.dept_view, false),
        delBtn: this.validData(this.permission.dept_delete, false),
        editBtn: this.validData(this.permission.dept_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  methods: {
    initData(tenantId) {
      getDeptTree(tenantId).then(res => {
        const column = this.findColumn(this.option.column, 'parentId');
        column.dicData = res.data.data;
      });
    },
    handleParentChange(parentId) {
      this.loadParentDeptCode(parentId);
    },
    loadParentDeptCode(parentId) {
      this.parentDeptCode = '';
      this.parentDept = null;
      if (!parentId || String(parentId) === '0') return;
      getDept(parentId).then(res => {
        this.parentDept = res.data.data || null;
        this.parentDeptCode = this.parentDept?.deptCode || '';
        this.updateDeptCategoryOptions();
      });
    },
    updateDeptCategoryOptions() {
      const categoryColumn = this.findColumn(this.option.column, 'deptCategory');
      const parent = this.parentDept;
      if (!parent) return;
      let dicData = [];
      if (this.isRootDept(parent)) {
        dicData =
          parent.deptName === '外部组织'
            ? [{ label: '承运商', value: 6 }]
            : [{ label: '集团', value: 1 }];
      } else if (Number(parent.deptCategory) === 1) {
        dicData = [
          { label: '事业部', value: 2 },
          { label: '部门', value: 3 },
        ];
      } else if ([2, 3].includes(Number(parent.deptCategory))) {
        dicData = [
          { label: '分公司', value: 4 },
          { label: '物流园区', value: 5 },
          { label: '承运商', value: 6 },
        ];
      }
      categoryColumn.dicData = dicData;
      if (!dicData.some(item => item.value === Number(this.form.deptCategory))) {
        this.form.deptCategory = dicData[0]?.value;
      }
      if (Number(this.form.deptCategory) === 6) {
        this.openCarrierDialog();
      }
    },
    handleDeptCategoryChange(value) {
      if (Number(value) === 6) {
        this.openCarrierDialog();
      }
    },
    openCarrierDialog() {
      this.carrierDialogVisible = true;
      this.loadCarrierList();
    },
    loadCarrierList() {
      getCustomerArchiveList(this.carrierPage.current, this.carrierPage.size, {
        ...this.carrierQuery,
        customerType: '承运商',
      }).then(res => {
        const page = res.data.data || {};
        this.carrierData = page.records || [];
        this.carrierPage.total = page.total || 0;
      });
    },
    searchCarrier() {
      this.carrierPage.current = 1;
      this.loadCarrierList();
    },
    resetCarrierQuery() {
      this.carrierQuery = { fullName: '', accessType: '', approvalStatus: '', status: undefined };
      this.searchCarrier();
    },
    handleCarrierSizeChange(size) {
      this.carrierPage.size = size;
      this.carrierPage.current = 1;
      this.loadCarrierList();
    },
    selectCarrier(row) {
      this.form.carrierCustomerId = row.id;
      this.form.deptName = row.fullName;
      this.form.shortName = row.shortName;
      this.form.mnemonicCode = row.mnemonicCode;
      this.carrierDialogVisible = false;
    },
    formatAccessType(value) {
      return value === 'formal' ? '正式' : value === 'temporary' ? '临时' : '-';
    },
    formatApprovalStatus(value) {
      const statusMap = {
        draft: '草稿',
        reviewing: '审核中',
        approved: '审核通过',
        rejected: '审核不通过',
      };
      return statusMap[value] || '-';
    },
    loadLeaderOptions(tenantId) {
      getLeaderList(tenantId).then(res => {
        this.leaderOptions = res.data.data || [];
      });
    },
    getDeptCategoryLabel(deptCategory) {
      const categoryMap = {
        1: '集团',
        2: '事业部',
        3: '部门',
        4: '分公司',
        5: '物流园区',
        6: '承运商',
      };
      return categoryMap[Number(deptCategory)] || '-';
    },
    getLeaderValue(leaderId, field) {
      const values = func.split(leaderId);
      const result = values
        .map(id => this.leaderOptions.find(item => String(item.id) === String(id))?.[field])
        .filter(Boolean);
      return result.length ? result.join('、') : '-';
    },
    isRootDept(row) {
      return row && (row.parentId === 0 || String(row.parentId) === '0');
    },
    handleAdd(row) {
      this.parentId = row.id;
      this.loadParentDeptCode(row.id);
      const column = this.findColumn(this.option.column, 'parentId');
      column.value = row.id;
      column.addDisabled = true;
      this.$refs.crud.rowAdd();
    },
    rowSave(row, done, loading) {
      row.tenantId = row.tenantId || this.userInfo.tenantId || website.tenantId;
      row.deptCode = String(row.deptCode || '').trim();
      row.leaderId = func.join(row.leaderId);
      if (Number(row.deptCategory) === 6 && !row.carrierCustomerId) {
        this.$message.warning('请选择承运商');
        loading();
        return;
      }
      add(row).then(
        res => {
          // 获取新增数据的相关字段
          const data = res.data.data;
          row.id = data.id;
          row.deptCategoryName = data.deptCategoryName;
          row.tenantId = data.tenantId;
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          // 数据回调进行刷新
          done(row);
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      row.tenantId = row.tenantId || this.userInfo.tenantId || website.tenantId;
      row.deptCode = String(row.deptCode || '').trim();
      row.leaderId = func.join(row.leaderId);
      if (Number(row.deptCategory) === 6 && !row.carrierCustomerId) {
        this.$message.warning('请选择承运商');
        loading();
        return;
      }
      update(row).then(
        () => {
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          // 数据回调进行刷新
          done(row);
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row, index, done) {
      if (this.isRootDept(row)) {
        this.$message.warning('根节点不能删除');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          // 数据回调进行刷新
          done(row);
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      const deletableRows = this.selectionList.filter(row => !this.isRootDept(row));
      if (deletableRows.length === 0) {
        this.$message.warning('根节点不能删除');
        return;
      }
      if (deletableRows.length !== this.selectionList.length) {
        this.$message.warning('根节点不能删除，已忽略根节点');
      }
      const deletableIds = deletableRows.map(row => row.id).join(',');
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(deletableIds);
        })
        .then(() => {
          // 刷新表格数据并重载
          this.data = [];
          this.parentId = 0;
          this.$refs.crud.refreshTable();
          this.$refs.crud.toggleSelection();
          // 表格数据重载
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    searchReset() {
      this.query = {};
      this.parentId = 0;
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.parentId = '';
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    beforeOpen(done, type) {
      if (type === 'add') {
        this.form.tenantId = this.form.tenantId || this.userInfo.tenantId || website.tenantId;
        this.initData(this.form.tenantId);
        this.loadParentDeptCode(this.form.parentId);
      }
      if (type === 'edit') {
        this.initData(this.form.tenantId || this.userInfo.tenantId || website.tenantId);
      }
      if (['edit', 'view'].includes(type)) {
        getDept(this.form.id).then(res => {
          this.form = Object.assign(res.data.data, {
            hasChildren: this.form.hasChildren,
          });
          if (this.form.parentId === '0') {
            this.form.parentId = '';
          }
          this.loadParentDeptCode(this.form.parentId);
          if (this.form.hasOwnProperty('leaderId')) {
            this.form.leaderId = func.split(this.form.leaderId);
          }
        });
      }
      done();
    },
    beforeClose(done) {
      this.parentId = '';
      this.parentDeptCode = '';
      this.parentDept = null;
      const column = this.findColumn(this.option.column, 'parentId');
      column.value = '';
      column.addDisabled = false;
      done();
    },
    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;
      getLazyList(this.parentId, Object.assign(params, this.query)).then(res => {
        this.data = res.data.data;
        this.loading = false;
        this.selectionClear();
      });
    },
    treeLoad(tree, treeNode, resolve) {
      const parentId = tree.id;
      getLazyList(parentId).then(res => {
        resolve(res.data.data);
      });
    },
  },
};
</script>

<style scoped>
.carrier-search-form {
  padding: 12px 12px 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.carrier-pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}

/* 操作列兜底：确保「查看 / 编辑 / 删除 / 新增子项」横向排列并保留 8px 间距，
   避免退化成 block 导致操作项竖排错位。全局样式已统一处理，此处为双保险。 */
:deep(.avue-crud__menu) {
  display: inline-flex !important;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  justify-content: flex-start;
  width: 100%;
  text-align: left;

  > .el-button,
  > .el-link,
  > .el-dropdown {
    flex-shrink: 0;
    display: inline-flex;
  }
}
</style>
