<template>
    <div class="app-container" id="">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item prop="startTime">
          <el-date-picker
            v-model="queryParams.startTime"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="开始日期"
            @change="() => queryParams.endTime = ''"
            style="width: 130px"
          />
        </el-form-item>
        <el-form-item>-</el-form-item>
        <el-form-item prop="endTime">
          <el-date-picker
            v-model="queryParams.endTime"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="结束日期"
            :picker-options="{ disabledDate: (t) => t.getTime() < new Date(queryParams.startTime).getTime() - 86400000}"
            style="width: 130px"
          />
        </el-form-item>
        <el-form-item prop="keyWord">
          <el-input
            v-model="queryParams.keyWord"
            placeholder="请输入关键字"
            clearable :maxlength="20"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item prop="unitId">
            <treeselect
                v-model="queryParams.unitId"
                :options="unitList" :normalizer="normalizer"
                :show-count="true" style="width: 240px" :disable-branch-nodes="true"
                noChildrenText="没有数据了" noOptionsText="没有数据" noResultsText="没有搜索结果"
                placeholder="请选择退料单位" @select="unitChange"
            />
        </el-form-item>
        <el-form-item prop="proId">
            <treeselect
                v-model="queryParams.proId"
                :options="proList" :normalizer="normalizer"
                :show-count="true" style="width: 240px" :disable-branch-nodes="true"
                noChildrenText="没有数据了" noOptionsText="没有数据" noResultsText="没有搜索结果"
                placeholder="请选择退料工程" @select="proChange"
            />
        </el-form-item>
        <el-form-item prop="typeName">
            <el-input
                v-model="queryParams.typeName"
                placeholder="请输入机具名称"
                clearable :maxlength="20"
                style="width: 240px"
            />
        </el-form-item>
        <el-form-item prop="impUnitName">
            <el-select v-model="queryParams.impUnitName" placeholder="请选择分公司" clearable style="width: 240px">
                <el-option
                    v-for="item in impUnitNameList"
                    :key="item.impUnitName"
                    :label="item.impUnitName"
                    :value="item.impUnitName"
                ></el-option>
            </el-select>
        </el-form-item>


        <el-form-item>
            <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
                >查询</el-button
            >
            <el-button
                icon="el-icon-refresh"
                size="mini"
                @click="resetQuery"
                >重置</el-button
            >
            <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                >导出</el-button
            >
        </el-form-item>
      </el-form>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      <el-table v-loading="loading" :data="tableList" border :max-height="650">
          <el-table-column label="序号" align="center" type="index">
                <template scope="scope">
                    <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index+1 }}</span>
                </template>
          </el-table-column>
          <el-table-column label="分公司" align="center" prop="impUnitName" width="150px":show-overflow-tooltip="true"/>
          <el-table-column label="退料单位" align="center" prop="backUnitName" />
          <el-table-column label="退料工程" align="center" prop="projectName" />
          <el-table-column label="维修单号" align="center" prop="repairCode"  :show-overflow-tooltip="true"/>
          <el-table-column label="机具名称" align="center" prop="typeName" :show-overflow-tooltip="true"/>
          <el-table-column label="规格型号" align="center" prop="typeModelName" :show-overflow-tooltip="true"/>
          <el-table-column label="设备编号" align="center" prop="maCode" :show-overflow-tooltip="true"/>
          <el-table-column label="操作" align="center" >
            <template slot-scope="scope">
                <el-button size="mini" type="success"   @click="handleRecord(scope.row)">试验记录单</el-button>
            </template>
          </el-table-column>
      </el-table>
      <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          @pagination="getList"
      />

    <!-- 弹框 -->
    <el-dialog title="试验记录表" :visible.sync="dialogVisible" width="46%" @close="closeDialog">
      <div  id="print-content3">
        <vue-easy-print tableShow ref="remarksPrintRef2" class="print" style="margin: 0 20px">
          <div style="text-align: center; font-weight: 600; font-size: 30px">机具（物流）分公司动力设备维修及试验记录单</div>
            <div class="info" style="margin: 10px 20px 0; display: flex; justify-content: space-between;">
                  <div
                        class="item"
                        style="flex-shrink: 0;margin-bottom: 5px;font-size: 14px;">
                        <span>退料单号：{{this.printInfo.code}}</span>
                    </div>
                    <div
                        class="item"
                        style="flex-shrink: 0;margin-bottom: 5px;font-size: 14px;">
                        <span>提交日期：{{this.printInfo.createTime}}</span>
                    </div>
                    <div class="item" style="flex-shrink: 0;margin-bottom: 5px;font-size: 14px;">
                        <span>设备编号：{{this.printInfo.maCode}}</span>
                    </div>
          </div>

          <div style="border: 3px solid #000; min-height: 600px; line-height: 3; display: flex; flex-direction: column; justify-content: space-between;">
            <div style="flex: 1; overflow: auto;">
            <div style="font-weight: 800; border-bottom: 1px solid #888; display: flex">
              <div style="width: 100%; padding-left: 10px;text-align: center">{{this.printInfo.typeName }}</div>
            </div>
            <div v-for="(group, groupIndex) in groupPrintData" :key="groupIndex" style="display: flex; border-bottom: 1px solid #000">
              <!-- 遍历分组中的每个元素，每个元素生成 name 和 status 两个表格 -->
              <div v-for="(row, index) in group" :key="index" style="flex: 1; display: flex; border-right: 1px solid #000;">
                <div style="flex: 1; text-align: center; border-right: 1px solid #000; padding: 3px;">
                  <span style="display: block;">{{ row.partName || '' }}</span>
                </div>
                <div style="flex: 1; text-align: center; padding: 3px;">
                  <span style="display: block;">{{ row.status || '' }}</span>
                </div>
              </div>
            </div>
            </div>
          <div style="flex-shrink: 0;">
            <div style="font-weight: 800; border-bottom: 1px solid #888;border-top: 1px solid #888; display: flex">
              <div style="width: 20%; text-align: center;border-right: 1px solid #888;">其他</div>
              <div style="width: 80%; text-align: center; display: flex; justify-content: space-between; ">
                <span style="margin-left: 25px;">{{otherData}}</span>
              </div>
            </div>
            <div style="font-weight: 800; border-bottom: 1px solid #888; display: flex">
              <div style="width: 20%; text-align: center;border-right: 1px solid #888;">空载试验</div>
              <div style="width: 80%; text-align: center; display: flex; justify-content: space-between; ">
                <span style="margin-left: 25px;">合格<span style="letter-spacing: 1.5em;">（<img v-if="printInfo && printInfo.scrapNum === 0" src="../../../../assets/img/yes.png" alt="√" style="vertical-align: middle; height: 1em; margin: 0 1.2em 0 0; display: inline-block;"/>）</span></span>
                <span style="margin-right: 200px;">不合格<span :style="{ letterSpacing: printInfo && printInfo.scrapNum > 0 ? '1.0em' : '2em' }">（
                  <img v-if="printInfo && printInfo.scrapNum > 0" src="../../../../assets/img/yes.png" alt="√" style="vertical-align: middle; height: 1em; margin: 0 1.2em 0 0; display: inline-block;"/>
                ）</span></span>
              </div>
            </div>

            <div style="font-weight: 800; border-bottom: 1px solid #888; display: flex">
              <div style="width: 20%; text-align: center;border-right: 1px solid #888;">标识是否齐全</div>
              <div style="width: 80%; text-align: center; display: flex; justify-content: space-between;">
                <span style="margin-left: 10px;">二维码<span style="letter-spacing: 1.5em;">（<img src="../../../../assets/img/yes.png" alt="√" style="vertical-align: middle; height: 1em; margin: 0 1.2em 0 0; display: inline-block;"/>）</span></span>
                <span>铭牌<span style="letter-spacing: 1.5em;">（<img src="../../../../assets/img/yes.png" alt="√" style="vertical-align: middle; height: 1em; margin: 0 1.2em 0 0; display: inline-block;"/>）</span></span>
                <span>档位<span style="letter-spacing: 1.5em;">（<img src="../../../../assets/img/yes.png" alt="√" style="vertical-align: middle; height: 1em; margin: 0 1.2em 0 0; display: inline-block;"/>）</span></span>
              </div>
            </div>

            <div style="font-weight: 800; border-bottom: 1px solid #888; display: flex">
              <div style="width: 60%;  display: flex; flex-direction: column;">
                <!-- 第一行：试验记录标题 -->
                <div style="display: flex; border-bottom: 1px solid #888;height: 40px;">
                  <div style="flex: 1; text-align: center; border-right: 1px solid #888;">额定负载</div>
                  <div style="flex: 1; text-align: center; border-right: 1px solid #888;">试验负载(t/MPa)</div>
                  <div style="flex: 1; text-align: center;">持荷时间(分/秒)</div>
                </div>
                <!-- 第二行：试验记录结果 -->
                <div style="display: flex; border-bottom: 1px solid #888;height: 40px;">
                  <div style="flex: 1; text-align: center; border-right: 1px solid #888;">{{ testResult1 || '' }}</div>
                  <div style="flex: 1; text-align: center; border-right: 1px solid #888;">{{ testResult2 || '' }}</div>
                  <div style="flex: 1; text-align: center;">{{ testResult3 || '' }}</div>
                </div>
                <!-- 第三行：试验日期、检验人员、提交人员标题 -->
                <div style="display: flex; border-bottom: 1px solid #888;height: 40px;">
                  <div style="flex: 1; text-align: center; border-right: 1px solid #888;">试验日期</div>
                  <div style="flex: 1; text-align: center; border-right: 1px solid #888;">检修人员</div>
                  <div style="flex: 1; text-align: center;">试验人员</div>
                </div>
                <!-- 第四行：对应结果 -->
                <div style="display: flex;height: 40px;">
                  <div style="flex: 1; text-align: center; border-right: 1px solid #888;">{{ formatDate(printInfo.createTime) }}</div>
                  <div style="flex: 1; text-align: center; border-right: 1px solid #888;">{{ this.printInfo.repairer }}</div>
                  <div style="flex: 1; text-align: center;">{{  this.printInfo.repairer }}</div>
                </div>
              </div>
              <!-- 右边部分，占三分之一 -->
              <div style="width: 40%; display: flex; border-left: 1px solid #888;">
                <!-- 第一列：试验结论 -->
                <div style="width: 25%;text-align: center; display: flex; flex-direction: column; justify-content: center; border-right: 1px solid #888;">
                  <span>试验结论</span>
                </div>
                <!-- 第二列：合格 -->
                <div style="width: 75%; padding: 0;">
                  <input 
                    type="text"
                    v-model="testConclusion"
                    style="
                      width: 100%;
                      height: 100%;
                      font-size: 64px;
                      color: red;
                      font-weight: bold;
                      border: none;
                      outline: none;
                      box-sizing: border-box;
                      text-align: center;
                      background-color: white;
                      font-family: SimSun;
                    "
                  />
                </div>
              </div>
            </div>
          </div>
          </div>

          <div class="fillIn" style="margin-top: 10px; display: flex; justify-content: space-between">
            <div class="item" style="width: 33%">
              <div>
                <span>审核：</span>
              </div>
            </div>

            <div class="item" style="width: 33%">
              <div>
                <span>检验员：{{ '高民' }}</span>
              </div>
            </div>
          </div>
        </vue-easy-print>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="print">打 印</el-button>
        <el-button @click="closeDialog">关 闭</el-button>
      </div>
    </el-dialog>



    </div>
</template>

<script>
import {
  getTestRecordApi,
  getTestRecordDetails
} from '@/api/stquery/stquery';
import {
    getProjectList,
    getUnitList,
    getImpUnitNameListApi,
} from '@/api/back/index.js'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import printJS from 'print-js'
export default {
    name: 'TestRecord',
    dicts: [],
    components: { Treeselect },
    data() {
        return {
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 弹出层标题
            title: '查看',
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            selectTreeProps: {
                children: 'children',
                label: 'name',
                // multiple: false,
                value: 'id',
                // multiple: true,
            },
            unitId: null,
            projectId: null,
            unitList: [],
            proList: [],
            // 总条数
            total: 0,
            // 主表格数据
            tableList: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                time: null,
                unitId: null,
                proId: null,
                keyWord: null,
                typeName: null, //物资名称
                statusName: null, //状态
                startTime: null,
                endTime: null,
                impUnitName: null, //分公司
            },
            dialogVisible: false, // 弹框显示
            printTableData: [], 
            printOtherData: [],
            otherData: "", //其他
            printInfo:{},
            testResult1: '',
            testResult2: '',
            testResult3: '',
            testConclusion: '合格',
            impUnitNameList: [],
        }
    },
    computed: {
        groupPrintData() {
            const result = [];
            console.log("xxxxxxxxxxxxx",this.printTableData.length)
            for (let i = 0; i < this.printTableData.length; i += 2) {
                const group = this.printTableData.slice(i, i + 2);
                // 若分组不足 2 个元素，补充空对象
                while (group.length < 2) {
                    group.push({ partName: '', status: '' });
                }
                result.push(group);
            }
            return result;
        },
    },
    created() {
        const end = new Date()
        let start = new Date()
        start.setMonth(start.getMonth() - 1)
        this.queryParams.startTime = this.format(start)
        this.queryParams.endTime = this.format(end)
        this.initSelectData()
        this.getImpUnitNameList()
        this.getList()
    },
    methods: {
      format(date) {
        const y = date.getFullYear()
        const m = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        return `${y}-${m}-${day}`
      },

        // 定义格式化日期的方法
      formatDate(dateStr) {
        if (!dateStr) return '';
        const date = new Date(dateStr);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      },

      initSelectData() {
          this.GetUnitData()
          this.GetProData()
      },
      /** 转换菜单数据结构 */
      normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                id: node.id,
                label: node.name,
                children: node.children,
            };
        },

      // 分公司下拉
      async getImpUnitNameList () {
          try {
              const res = await getImpUnitNameListApi()
              this.impUnitNameList = res.data
          } catch (error) {
              console.log('🚀 ~ error:', error)
          }
      },       
      // 获取 来往单位 列表数据
      async GetUnitData() {
              const params = {
                //   projectId: this.queryParams.proId /*  */,
              }
              const res = await getUnitList(params)
              this.unitList = res.data
      },
      unitChange(val){
        //   if(val&&val.length>0){
        //       this.queryParams.unitId=this.unitId[this.unitId.length - 1]
        //   }else if(val&&val.length==0){
        //       this.queryParams.unitId=""
        //   }
        //   this.GetProData()
        setTimeout(()=>{
            this.GetProData()
        },500)
      },
      // 获取 工程名称 列表数据
      async GetProData() {
              const params = { unitId: this.queryParams.unitId}
              const res = await getProjectList(params)
              this.proList = res.data
              this.queryParams.proId=null
      },
      proChange(val){
        //   if(val&&val.length>0){
        //       this.queryParams.proId=this.projectId[this.projectId.length - 1]
        //   }else if(val&&val.length==0){
        //       this.queryParams.proId=""
        //   }
        //   this.GetUnitData()
        setTimeout(()=>{
            this.GetUnitData()
        },500)
      },

      // 获取列表
      async getList() {
        try {
            this.loading = true
            const params = {
                  unitId: this.queryParams.unitId,
                  proId: this.queryParams.proId,
                  keyWord: this.queryParams.keyWord,
                  typeName: this.queryParams.typeName,
                  statusName: this.queryParams.statusName,
                  impUnitName: this.queryParams.impUnitName,
                  startTime: this.queryParams.startTime,
                  endTime: this.queryParams.endTime,
                  pageSize: this.queryParams.pageSize,
                  pageNum: this.queryParams.pageNum
              }
            const res = await getTestRecordApi(params)
            this.loading = false
            if(res.rows.length>0){
              this.tableList = res.rows;
            }else{
              this.tableList=[]
            }
            this.total = res.total;
        } catch (error) {
            this.loading = false
        } finally {
            this.loading = false
        }
      },
      /** 搜索按钮操作 */
      handleQuery() {
          this.queryParams.pageNum = 1
          this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        const end = new Date()
        let start = new Date()
        start.setMonth(start.getMonth() - 1)
        this.queryParams.startTime = this.format(start)
        this.queryParams.endTime = this.format(end)
        this.unitId=[]
        this.projectId=[]
        this.resetForm('queryForm')
        this.handleQuery()
      },

        async handleRecord(row){
        this.dialogVisible = true;
        this.printTableData = [];
        this.printOtherData = [];
        this.otherData = "";
        let param  = {
            id:row.id,
        }
        const res = await getTestRecordDetails(param)
        this.printInfo = res.data[0]
        if(this.printInfo && this.printInfo.ratedLoad) {
            this.testResult1 = this.printInfo.ratedLoad + '(t/MPa)'
        } else {
            this.testResult1 = ''
        }
        if(this.printInfo && this.printInfo.testLoad) {
            this.testResult2 = this.printInfo.testLoad + '(t/MPa)'
        } else {
            this.testResult2 = ''
        }
        if(this.printInfo && this.printInfo.holdingTime) {
            this.testResult3 = this.printInfo.holdingTime + '(分/秒)'
        } else {
            this.testResult3 = ''
        }
        if(res.data[0].partTypeList&& res.data[0].partTypeList.length != 0){
            res.data[0].partTypeList.forEach((e) => {
              if(e.isSure == 1 && e.isShow == 1){
                this.printTableData.push({'partName':e.partName,'status':'更换'})
              }else if(e.isSure == 1 && e.isShow == 0){
                this.printTableData.push({'partName':e.partName,'status':'合格'})
              }else if(e.isSure == 0 && e.isShow == 0){
                this.printOtherData.push({'partName':e.partName,'status':''})
                this.otherData =  this.otherData + e.partName + '、'
              }
            })
              // 去除最后一个逗号
              if(this.otherData.length > 0){
                this.otherData = this.otherData.substring(0, this.otherData.length - 1)
              }
        }
        },

        // 打印
        print() {
            printJS({
            printable: 'print-content3',
            type: 'html', //
            // targetStyles: ['*'], // 打印的元素样式
            scanStyles: false, // 是否扫描页面样式
            // css: [
            //   'https://unpkg.com/element-ui/lib/theme-chalk/index.css' // Element UI 的样式表
            // ],
            maxWidth: '1400'
            // 其他配置选项
            })
        },

        // 关闭弹框并清除数据
        closeDialog() {
            this.dialogVisible = false; // 关闭弹框
            this.printInfo = {}; // 清空数据
            this.printTableData = []; // 清空表格数据
            this.printOtherData = []; // 清空表格数据
            this.otherData = ""; // 清空表格数据
            this.testResult1 = '';
            this.testResult2 = '';
            this.testResult3 = '';
            this.testConclusion = '合格';
        },       

      /** 导出按钮操作 */
      handleExport() {
        const formatTime = (date) => {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          const hours = String(date.getHours()).padStart(2, '0');
          const minutes = String(date.getMinutes()).padStart(2, '0');
          const seconds = String(date.getSeconds()).padStart(2, '0');
          return `${year}${month}${day}_${hours}${minutes}${seconds}`;
        };
        const params = {
            unitId: this.queryParams.unitId,
            proId: this.queryParams.proId,
            keyWord: this.queryParams.keyWord,
            typeName: this.queryParams.typeName,
            statusName: this.queryParams.statusName,
            startTime: this.queryParams.startTime,
            endTime: this.queryParams.endTime,
            pageSize: this.queryParams.pageSize,
            pageNum: this.queryParams.pageNum
        }
        const currentTime = formatTime(new Date());
          this.download(
              'material/repair/getTestRecordExport',
              {
                  ...params,
              },
              `试验记录_${currentTime}.xlsx`,
          )
      },

    },
}
</script>
<style lang="scss" scoped>
::v-deep.el-table .fixed-width .el-button--mini {
    width: 60px !important;
    margin-bottom: 10px;
}
.clickText {
  color: #02a7f0;
  cursor: pointer;
}
</style>
