<template>
  <ele-modal
    title="售后工单查询"
    custom-class="ele-dialog-form long-dialog-form"
    :visible.sync="visible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    width="70%"
    :maxable="true"
    :resizable="true"
  >
    <el-card shadow="never" v-loading="loading">
      <work-search
        class="seep-search"
        ref="workSearch"
        :levelList="levelList"
        @search="reload"
      ></work-search>

      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        row-key="id"
        height="calc(100vh - 500px)"
        class="dict-table"
      >
        <template v-slot:toolbar></template>
        <template v-slot:faultLevel="{ row }">
          {{ levelData[row.faultLevel] || '' }}
        </template>
       <template v-slot:selection="{ row }">
  <div class="radio-container">
    <el-radio
      v-model="selectedRowId"
      :label="row.id"
      @change="() => selectedRow = row"
    ><span></span></el-radio>
  </div>
</template>
      </ele-pro-table>
    </el-card>

    <div class="btns" slot="footer">
      <el-button 
        type="primary" 
        size="small" 
        :disabled="!selectedRow"
        @click="handleConfirm"
      >
        确认
      </el-button>
      <el-button size="small" @click="handleClose">关闭</el-button>
    </div>
  </ele-modal>
</template>

<script>
import workSearch from './work-search.vue';
import { getSalesWorkOrder } from '@/api/salesServiceManagement/index';
import { getByCode } from '@/api/system/dictionary-data';
import dictMixins from '@/mixins/dictMixins';

export default {
  mixins: [dictMixins],
  components: {
    workSearch
  },
  data() {
    return {
      visible: false,
      loading: false,
      levelData: {},
      levelList: [],
      selectedRowId: null,
      selectedRow: null,  // 存储选中的完整行数据
      columns: [
        {
          columnKey: 'selection',
          label: '选择',
          slot: 'selection',
          align: 'center',
          showOverflowTooltip: true,
          fixed: 'left'  // 固定选择列在左侧，避免滚动后看不到
        },
        {
          columnKey: 'index',
          label: '序号',
          type: 'index',
          width: 55,
          align: 'center',
          showOverflowTooltip: true,
          fixed: 'left'
        },
        {
          prop: 'code',
          label: '工单编号',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 150
        },
        {
          prop: 'planCode',
          label: '计划单号',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 110
        },
        {
          prop: 'planName',
          label: '计划名称',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 110
        },
        {
          prop: 'executeUserName',
          label: '报工人',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 110
        },
        {
          prop: 'accepterUserName',
          label: '验收人',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 110
        },
        {
          slot: 'faultLevel',
          prop: 'faultLevel',
          label: '故障等级',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 110
        },
        {
          prop: 'contactName',
          label: '客户名称',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 110
        },
        {
          prop: 'categoryName',
          label: '设备名称',
          align: 'center',
          minWidth: 110,
          showOverflowTooltip: true,
          formatter: (row) => {
            if (!row.deviceDetails) return '';
            return row.deviceDetails.map((el) => el.categoryName).join(',');
          }
        },
        {
          prop: 'accepterTime',
          label: '验收时间',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 110
        },
        {
          prop: 'totalCost',
          label: '费用( 元 )',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 110
        },
        {
          columnKey: 'inFactDuration',
          label: '工时',
          align: 'center',
          resizable: false,
          showOverflowTooltip: true,
          minWidth: 120,
          formatter: (row) => {
            if (row.inFactDuration || row.inFactDuration === 0) {
              return `${((row.inFactDuration - 0) / 60).toFixed(1)} 小时`;
            }
            return '';
          }
        },
        {
          prop: 'orderStatus',
          label: '状态',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 110,
          formatter: (row) => {
            const statusMap = {
              0: '待执行',
              1: '已接收',
              2: '执行中',
              3: '待验收',
              4: '待评价',
              5: '已完成',
              6: '验收不通过'
            };
            return statusMap[row.orderStatus] || '';
          }
        }
      ]
    };
  },
  created() {
    this.getLevelCode('fault_level');
  },
  methods: {
    open() {
      this.visible = true;
      this.reload();
    },
    async getLevelCode(code) {
      const res = await getByCode(code);
      if (res?.code === '0') {
        this.levelData = res.data.reduce((obj, el) => {
          const key = Object.keys(el)[0];
          obj[key] = Object.values(el)[0];
          return obj;
        }, {});
        this.levelList = res.data.map((el) => ({
          label: Object.values(el)[0],
          value: Object.keys(el)[0]
        }));
      }
    },
    datasource({ page, limit, where }) {
      this.loading = true;
      const params = {
        pageNum: page,
        size: limit,
        ...where
      };
      return getSalesWorkOrder(params).finally(() => {
        this.loading = false;
      });
    },
    reload(where = {}) {
      this.$refs.table?.reload({
        pageNum: 1,
        where: where
      });
    },
    // 新增：确认按钮逻辑，向父组件传递选中数据
    handleConfirm() {
      if (this.selectedRow) {
        console.log(this.selectedRow)
        
        this.$emit('changeParent', this.selectedRow);
        this.handleClose();  // 确认后关闭弹窗
      }
    },
    handleClose() {
      this.visible = false;
      // 重置选中状态，避免下次打开残留选中
      this.selectedRowId = null;
      this.selectedRow = null;
      this.$refs.table?.reload({ pageNum: 1 });
    }
  }
};
</script>

<style lang="scss" scoped>
.seep-search {
  margin-bottom: 16px;
  ::v-deep .el-input__inner {
    padding: 0 5px 0 10px;
  }
}

.btns {
  text-align: center;
  padding: 10px 0;
  button:first-child {  // 给确认按钮加右边距，和关闭按钮分隔
    margin-right: 8px;
  }
}

::v-deep .ele-pro-table {
  margin-top: 8px;
}

::v-deep .el-radio {
  vertical-align: middle;
}
.radio-container {
  text-align: center; /* 让单选框居中 */
  line-height: 1;     /* 消除行高导致的多余空间 */
}
::v-deep .radio-container .el-radio {
  display: inline-block; /* 确保单选框独占空间 */
}
</style>