<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="4" :lg="5" :md="7" :sm="24">
            <a-form-item label="工单">
              <a-input placeholder="请输入工单" v-model="queryParam.workOrder"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="5" :md="7" :sm="24">
            <a-form-item label="工具">
              <a-input placeholder="请输入工具" v-model="queryParam.toolId"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="5" :md="7" :sm="24">
            <a-form-item label="设备">
              <j-search-select-tag placeholder="要生成计划的设备" dict="v_bu_device,name,id" v-model="queryParam.deviceId" />
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
<!--            <a-col :xl="4" :lg="5" :md="7" :sm="24">
              <a-form-item label="部件">
                <a-input placeholder="请输入部件" v-model="queryParam.partId"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="4" :lg="5" :md="7" :sm="24">
              <a-form-item label="测量项点">
                <a-input placeholder="请输入测量项点" v-model="queryParam.regularInputId"></a-input>
              </a-form-item>
            </a-col>-->
            <a-col :xl="4" :lg="5" :md="7" :sm="24">
              <a-form-item label="测量人">
                <a-input placeholder="请输入测量人" v-model="queryParam.inspector"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="8" :lg="10" :md="12" :sm="24">
              <a-form-item label="测量时间">
                <j-date :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开始时间" class="query-group-cust" v-model="queryParam.inspecTime_begin"></j-date>
                <span class="query-group-split-cust"></span>
                <j-date :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束时间" class="query-group-cust" v-model="queryParam.inspecTime_end"></j-date>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
<!--      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>-->
      <a-button type="primary" icon="download" @click="handleExportXls('作业数据记录')">导出</a-button>
<!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">-->
<!--        <a-button type="primary" icon="import">导入</a-button>-->
<!--      </a-upload>-->
      <!-- 高级查询区域 -->
      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="workOrder" slot-scope="text">
          <a-button type="link" @click="workOrderView(text)">查看工单</a-button>
        </template>
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text,record">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>
        <template slot="regularInput" slot-scope="text, record">
          <a style="color:#1890ff" @click="openTrendModal(record)">
            {{ text }}
          </a>
        </template>
        <template slot="resultSlot" slot-scope="text,record">
          <p @click="checkOldVersion(record)">{{ text }}</p>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">详情</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a>删除</a>
          </a-popconfirm>
        </span>

      </a-table>
    </div>

    <work-record-modal ref="modalForm" @ok="modalFormOk"></work-record-modal>
    <work-order-detail-model :order-id="workOrder" :visible="detailModelVisible" @close="closeDetailModel"></work-order-detail-model>
    <a-modal
      :title="`测量值趋势分析（${currentRegularInputText || ''}）`"
      :visible="trendVisible"
      width="920px"
      :footer="null"
      @cancel="closeTrendModal"
    >
      <!-- 查询条件 -->
      <div style="margin-bottom: 12px;">
        <a-range-picker v-model="dateRange" :show-time="true" format="YYYY-MM-DD HH:mm:ss" style="width: 360px" />
        <a-button type="primary" icon="search" style="margin-left: 8px" @click="loadTrendData">
          查询
        </a-button>
      </div>

      <!-- 图表 -->
      <div ref="trendChart" style="width:100%;height:420px;"></div>
    </a-modal>
    <a-modal
      v-model="recordVisible"
      title="采集日志"
      width="40vw"
      :footer="null"
      @cancel="closeRecords"
    >
      <a-table
        bordered
        rowKey="id"
        :columns="rcolumns"
        :dataSource="rRecords"
        :loading="rloading"
        :pagination="false"
        :scroll="{ y: 350 }"
      >
        <template slot="resultSlot" slot-scope="text,record">
          <p :style="{
                backgroundColor: record.resultOverGauge ? '#d8ffe3' : '#ffd7d7'
              }">{{ text }}</p>
        </template>
      </a-table>
    </a-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import WorkRecordModal from './modules/WorkRecordModal'
  import WorkOrderDetailModel from '@views/workOrder/components/WorkOrderDetailModel/index.vue'
  import moment from 'moment'
  import * as echarts from 'echarts'
  import { getAction } from '@api/manage'

  export default {
    name: 'WorkRecordList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      WorkOrderDetailModel,
      WorkRecordModal
    },
    data () {
      return {
        description: '作业数据记录管理页面',
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'工单',
            align:"center",
            dataIndex: 'workOrder',
            scopedSlots: { customRender: 'workOrder' }
          },
          {
            title:'工具',
            align:"center",
            dataIndex: 'toolId_dictText'
          },
          {
            title:'设备',
            align:"center",
            dataIndex: 'deviceId_dictText'
          },
          {
            title:'部件',
            align:"center",
            dataIndex: 'partId_dictText'
          },
          {
            title:'测量项点',
            align:"center",
            dataIndex: 'regularInputId_dictText',
            scopedSlots: { customRender: 'regularInput' }
          },
          {
            title:'测量值',
            align:"center",
            dataIndex: 'numericValue',
            scopedSlots: { customRender: "resultSlot" },
          },
          {
            title:'单位',
            align:"center",
            dataIndex: 'unit'
          },
          {
            title:'测量人',
            align:"center",
            dataIndex: 'inspector'
          },
          {
            title:'测量时间',
            align:"center",
            dataIndex: 'inspecTime'
          },
          {
            title:'备注',
            align:"center",
            dataIndex: 'remark'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          list: "/workOrder/workRecord/list",
          listNoPage: "/workOrder/workRecord/list/nopage",
          delete: "/workOrder/workRecord/delete",
          deleteBatch: "/workOrder/workRecord/deleteBatch",
          exportXlsUrl: "/workOrder/workRecord/exportXls",
          importExcelUrl: "workOrder/workRecord/importExcel",

        },
        dictOptions:{},
        superFieldList:[],
        workOrder: null,
        detailModelVisible: false,
        trendVisible: false,
        currentRegularInputId: null,
        currentRegularInputText: '',
        trendChartInstance: null,
        dateRange: [],               // 手动日期范围
        currentMinValue: null,
        currentMaxValue: null,

        // 表头
        rcolumns: [
          {
            title:'版本',
            align:"center",
            width: 70,
            dataIndex: 'collectNum'
          },
          {
            title:'测量值',
            align:"center",
            width: 120,
            dataIndex: 'numericValue',
            scopedSlots: { customRender: "resultSlot" },
          },
          {
            title:'单位',
            align:"center",
            width: 90,
            dataIndex: 'unit'
          },
          {
            title:'测量人',
            align:"center",
            width: 100,
            dataIndex: 'inspector'
          },
          {
            title:'测量时间',
            align:"center",
            width: 200,
            dataIndex: 'inspecTime'
          },
          {
            title:'备注',
            align:"center",
            dataIndex: 'remark'
          },
        ],
        recordVisible: false,
        rRecords: [],
        rloading: false,
      }
    },
    created() {
    this.getSuperFieldList();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      openTrendModal(record) {
        this.currentRegularInputId = record.regularInputId
        this.currentRegularInputText = record.regularInputId_dictText
        // 保存上下限
        this.currentMinValue = record.minValue
        this.currentMaxValue = record.maxValue
        console.log(record.minValue, record.maxValue,record)
        // 默认近一年
        this.dateRange = [
          moment().subtract(1, 'year'),
          moment()
        ]
        this.trendVisible = true
        this.$nextTick(() => {
          this.loadTrendData()
        })
      },
      closeTrendModal() {
        this.trendVisible = false
        if (this.trendChartInstance) {
          this.trendChartInstance.dispose()
          this.trendChartInstance = null
        }
      },
      loadTrendData() {
        if (!this.currentRegularInputId) return

        const params = {
          regularInputId: this.currentRegularInputId,
          createTime_begin: this.dateRange && this.dateRange[0] ? this.dateRange[0].format('YYYY-MM-DD HH:mm:ss') : '',
          createTime_end: this.dateRange && this.dateRange[1] ? this.dateRange[1].format('YYYY-MM-DD HH:mm:ss') : ''
        }

        getAction(this.url.listNoPage, params).then(res => {
          if (res.success) {
            this.renderTrendChart(res.result || [])
          } else {
            this.$message.warning(res.message || '查询失败')
          }
        })
      },
      renderTrendChart(list) {
        if (!this.trendChartInstance) {
          this.trendChartInstance = echarts.init(this.$refs.trendChart)
        }

        // 按时间排序
        const sortedList = list.sort(
          (a, b) => new Date(a.inspecTime) - new Date(b.inspecTime)
        )

        const xData = []
        const yData = []

        sortedList.forEach(item => {
          xData.push(moment(item.inspecTime != null ? item.inspecTime : item.createTime).format('YYYY-MM-DD'))
          yData.push(item.numericValue)
        })

        // 构造上下限线
        const markLineData = []

        if (this.currentMinValue != null) {
          markLineData.push({
            yAxis: this.currentMinValue,
            name: '下限',
            lineStyle: {
              type: 'dashed',
              color: '#fa8c16'
            },
            label: {
              formatter: '下限: {c}'
            }
          })
        }

        if (this.currentMaxValue != null) {
          markLineData.push({
            yAxis: this.currentMaxValue,
            name: '上限',
            lineStyle: {
              type: 'dashed',
              color: '#ff4d4f'
            },
            label: {
              formatter: '上限: {c}'
            }
          })
        }

        this.trendChartInstance.setOption({
          tooltip: { trigger: 'axis' },
          grid: {
            left: '3%',
            right: 80,   // 用像素比百分比稳定
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: xData,
            boundaryGap: false
          },
          yAxis: {
            type: 'value',
            name: '测量值'
          },
          series: [
            {
              name: this.currentRegularInputText,
              type: 'line',
              smooth: true,
              data: yData,
              symbol: 'circle',
              symbolSize: 6,

              markLine: markLineData.length ? {
                silent: true,
                data: markLineData
              } : null
            }
          ]
        }, true)
      },
      checkOldVersion(record) {
        if(record.collectNum>1) {
          console.log("******", record.regularInputId)
          this.rloading = true;
          this.recordVisible = true;
          getAction(this.url.listNoPage,
            {regularInputId:record.regularInputId,workOrder:record.workOrder})
            .then(res=>{
              if (res.success) {
                this.rRecords = res.result;
              }
            }).finally(()=>{
              this.rloading = false;
          });
        }
      },
      closeRecords() {
        this.recordVisible = false;
        this.records = [];
      },
      initDictConfig() {
      },
      getSuperFieldList() {
        let fieldList = [];
        fieldList.push({ type: 'string', value: 'workOrder', text: '工单', dictCode: '' })
        fieldList.push({ type: 'string', value: 'toolId', text: '工具', dictCode: '' })
        fieldList.push({ type: 'string', value: 'deviceId', text: '设备', dictCode: '' })
        fieldList.push({ type: 'string', value: 'partId', text: '部件', dictCode: '' })
        fieldList.push({ type: 'string', value: 'regularInputId', text: '测量项点', dictCode: '' })
        fieldList.push({ type: 'string', value: 'numericValue', text: '测量值', dictCode: '' })
        fieldList.push({ type: 'string', value: 'unit', text: '单位', dictCode: '' })
        fieldList.push({ type: 'string', value: 'inspector', text: '测量人', dictCode: '' })
        fieldList.push({ type: 'datetime', value: 'inspecTime', text: '测量时间' })
        fieldList.push({ type: 'string', value: 'remark', text: '备注', dictCode: '' })
        this.superFieldList = fieldList
      },
      workOrderView(workOrderId) {
        this.workOrder = workOrderId;
        this.detailModelVisible = true;
      },
      closeDetailModel() {
        this.detailModelVisible = false;
        this.workOrder = null;
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>