<script>
import { getAction, postAction } from '@api/manage'

export default {
  name: 'OperationRecordList',
  props:{
    orderId:{
      type: String,
      default: '',
    }
  },
  data(){
    return{
      columns:[
        {
          title: '序号',
          dataIndex: 'dispOrder',
          width:60,
          align:"center",
        },
        {
          title:'检查类型',
          align:"center",
          width:75,
          dataIndex: 'checkType_dictText'
        },
        {
          title:'部件',
          align:"center",
          width:150,
          dataIndex: 'depard_dictText'
        },
        {
          title:'作业内容',
          align:"left",
          width:450,
          dataIndex: 'content',
          scopedSlots: { customRender: 'content' }
        },
        {
          title:'检查结果',
          align:"center",
          width:75,
          dataIndex: 'checkResult'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align:"center",
          fixed:"right",
          width:147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      dataSource:[],
      /* 分页参数 */
      ipagination:{
        current: 1,
        pageSize: 200,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 排序参数 */
      isorter:{
        column: 'createTime',
        order: 'desc',
      },
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading:false,
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      /* 查询折叠 */
      toggleSearchStatus:false,
      /* 高级查询条件生效状态 */
      superQueryFlag:false,
      /* 高级查询条件 */
      superQueryParams: '',
      /** 高级查询拼接方式 */
      superQueryMatchType: 'and',
      url:{
        list: "/workOrder/workOrder/getDetailbyId",
        delete: "/workOrder/operationRecord/delete",
        deleteBatch: "/workOrder/operationRecord/deleteBatch",
        exportXlsUrl: "/workOrder/operationRecord/exportXls",
        importExcelUrl: "workOrder/operationRecord/importExcel",
        completeRecord: "/workOrder/operationRecord/complete",
        addWorkOrder: "/workOrder/workRecord/add",
        insertWorkOrder: "/workOrder/workRecord/insert",
      }
    }
  },
  mounted() {
    this.loadDataSource()
  },
  methods:{
    handleMeasure(record){
      this.loading = true
      console.log("点击测量后",record)
      const data = {
        workOrder: this.orderId,
        workOrderDetail: record.id,
        regularId : record.regularId,
        content: record.content,
      }
      // 发送 post 请求
      postAction(this.url.insertWorkOrder, data)
        .then(res => {
          console.log("insertWorkOrder 响应", res)
          if(res.success){
            // 请求成功后的处理逻辑
            this.$message.info("请使用对应仪器进行测量，测量结果在工单详情中查看")
            // 刷新当前页面
            // location.reload()
          }
        })
        .catch(error => {
          console.error("insertWorkOrder 请求出错", error)
          this.$message.error("操作失败，请稍后重试")
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleCompleteAllSelectRecords(){
      this.loading = true
      console.log("this.selectedRowKeys",this.selectedRowKeys)
      const selectData = this.dataSource.filter(item => this.selectedRowKeys.includes(item.id))
      const needmeasure = selectData.filter(item => item.measure === 1).length > 0
      if(needmeasure){
        this.$message.warning("测量项无法一键完成检查")
        this.loading = false
        return
      }
      const data = new Map(this.selectedRowKeys.map(str => [str, 0]))
      const jsonData = Object.fromEntries(data);
      console.log('data',jsonData)
      postAction(this.url.completeRecord, jsonData)
        .then(res => {
          console.log("complete",res)
          if(res.success){
            this.loadDataSource()
          }
        }).finally(() => this.loading = false);
    },
    handleTableChange(){

    },
    onSelectChange(selectedRowKeys, selectionRows){
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    loadDataSource() {
      this.loading = true
      getAction(this.url.list, {id: this.orderId, queryAll:0}).then(res=>{
        if (res.success && res.result != null) {
          console.log("detail",res.result);
          this.dataSource = res.result.workOrderDetailModels;
          this.loading = false
        }
      })
    },
    handleCheck(record){
      this.loading = true;
      // 构造请求数据，这里假设只需要记录的 id，可根据实际需求调整
      const data = {
        [record.id]: 1
      };
      // 发送 post 请求
      postAction(this.url.completeRecord, data)
        .then(res => {
          console.log("completeRecord 响应", res);
          if(res.success){
            this.$message.success("检查完成");
            // 刷新数据
            this.loadDataSource();
          } else {
            this.$message.error("检查操作失败");
          }
        })
        .catch(error => {
          console.error("completeRecord 请求出错", error);
          this.$message.error("操作失败，请稍后重试");
        })
        .finally(() => {
          this.loading = false;
        });
    }
  }
}
</script>

<template>
  <div class="operation-record-container">
    <a-table
      v-if="this.dataSource && this.dataSource.length>0"
      ref="table"
             size="middle"
             :scroll="{x:true,y:740}"
             bordered
             rowKey="id"
             :columns="columns"
             :dataSource="dataSource"
             :pagination="ipagination"
             :loading="loading"
             :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
             class="j-table-force-nowrap"
             @change="handleTableChange">
        <span slot="action" slot-scope="text, record">
           <a v-if="record.measure === '1'" @click="handleMeasure(record)">测量</a>
           <a v-else @click="handleCheck(record)">检查</a>
        </span>
      <template #content="text">
        <div class="custom-column" :style="{maxWidth: '480px'}">
          {{ text }}
        </div>
      </template>
    </a-table>
    <a-result
      v-else-if="this.dataSource && this.dataSource.length == 0 && !this.loading"
      status="success"
      title="该工单已完成全部作业"
      :sub-title="'工单:' +  this.orderId + ' 作业内容已全部完成.'"
    >
    </a-result>
    <a-spin
      v-else
      size="large"
      :spinning="loading"
      :tip="'加载中...'"
      class="center-spin"
    >
    </a-spin>
  </div>

</template>

<style scoped>
.operation-record-container {
  position: relative;
  min-height: 400px;
}

.center-spin {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.custom-column {
  white-space: normal; /* 允许换行 */
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>