<template>
  <Dialog title="打印预览" v-model="dialogVisible" width="1000">
    <!-- 打印预览 -->
    <div class="print-wrap page" ref="print">
      <table border="2" cellspacing="0" id="table" style="height: 27.2cm;">
        <tbody>
        <tr>
          <td colspan="2">
            <div style="width: 100px; text-align: center">
              <img :src="logoDataUrl" style="width: 100%" alt="" />
            </div>
          </td>
          <td colspan="6">
            <span style="font-size: 20px; font-weight: 700">模具生产计划单</span>
          </td>
          <td colspan="2" style="padding: 5px 0">
            <div style="border-bottom: 1px solid #666; padding-bottom: 5px;font-size: 16px" >项目编号</div>
            <div style="padding-top: 5px; font-size: 16px" >{{ formData.code }}</div>
          </td>
        </tr>
        </tbody>
        <tbody class="masterClass">
        <tr>
          <td colspan="2" style="font-size: 16px"> 客户名称 </td>
          <td colspan="5">
            <span style="font-size: 16px">{{ formData.customerName }}</span>
          </td>
          <td colspan="1" style="font-size: 16px">{{ formData.customer.brief }}</td>
          <td style="font-size: 16px"> 编码： </td>
          <td style="font-size: 16px">{{ formData.customer.code }} </td>
        </tr>
        </tbody>
        <tbody class="masterClass">
                  <tr>
          <td colspan="2" style="font-size: 16px"> 项目名称 </td>
          <td colspan="6" style="font-size: 16px">
            {{ formData.projectName }}
          </td>
          <td style="font-size: 16px"> 业务员： </td>
          <td style="font-size: 16px">{{ formData.businessManName }} </td>
        </tr>
        <tr>
          <td colspan="2" style="font-size: 16px"> 项目工期 </td>
          <td  colspan="1" style="padding: 0 5px"> 起 </td>
          <td colspan="1" style="min-width: 70px;">{{ formatDate(new Date(formData.projectStartTime), 'YYYY-MM-DD') }}</td>
          <td colspan="1" style="min-width: 70px;">至</td>
          <td colspan="1" style="min-width: 70px;">{{ formatDate(new Date(formData.projectEndTime), 'YYYY-MM-DD') }}</td>
          <td style="min-width: 70px;">天数</td>
          <td colspan="1">{{ betweenDay(new Date(formData.projectStartTime), new Date(formData.projectEndTime)) +1 }}</td>
          <td colspan="1"> 是否有价格： </td>
          <td colspan="1">{{ getDictLabel(DICT_TYPE.HELI_COMMON_IS_OR_NOT, formData.hasPrice) }} </td>
        </tr>
        <tr  class="masterClass">
          <td colspan="2" style="font-size: 16px"> 项目负责人: </td>
          <td colspan="2" class="masterClass">{{ userInit.find((user) => user.id == planData.projectOwner)?.nickname }} </td>
          <td colspan="1">
            <!-- <div style="width: 100%; display: flex; justify-content: center; font-size: 12px"> -->
            <div>
              <div style="border-bottom: 1px solid #333; padding: 0 5px; height: 30%">类别：</div>
              <div style="padding: 0 5px; height: 30%">性质：</div>
            </div>
          </td>
          <td colspan="1">
            <!-- <div style="border: 1px solid #333"> -->
            <div style="border-bottom: 1px solid #333; padding: 0 5px; height: 30%">{{ getDictLabel(DICT_TYPE.HELI_BUSINESS_LINE, formData.businessLine) }}</div>
            <div style="padding: 0 5px; height: 30%">{{ getDictLabel(DICT_TYPE.HELI_PROJECT_PROPERTY, formData.property) }}</div>
            <!-- </div> -->
            <!-- </div> -->
          </td>
          <td colspan="4" >
            <div style="display: flex; justify-content: space-between">
              <div style="width: 100%; font-size: 12px; display: flex; flex-direction: column">
                <div style="text-align: left; width: 100; margin-left: 10px">自客户提供资料：</div>
                <div id="fruitForm" style="display: flex; justify-content: flex-start; align-items: center">
                  <span class="checkbox" v-if="formData.hasContract == 0"></span>
                  <span class="checkbox" v-else-if="formData.hasContract == 1">√</span>
                  <label for="checkbox1">合同</label>

                  <span class="checkbox" v-if="formData.hasTechnologyProtocol == 0"></span>
                  <span class="checkbox" v-else-if="formData.hasTechnologyProtocol == 1">√</span>
                  <label for="checkbox2">技术协议</label>
                  <span class="checkbox" v-if="formData.hasBlueprint == 0"></span>
                  <span class="checkbox" v-else-if="formData.hasBlueprint == 1">√</span>
                  <label for="checkbox3">图纸/数模</label>
                </div>
              </div>
            </div>
          </td>
        </tr>
        <tr>
          <td colspan="2" style="font-size: 16px">是否要工艺:</td>
          <td>

            {{ getDictLabel(DICT_TYPE.HELI_COMMON_IS_OR_NOT, planData.hasCraft) }}
          </td>
          <td>开始日期</td>
          <td>
            <span v-if="!planData.craftStartDate">&nbsp;</span>
            <span v-else>{{ formatDate(new Date(planData.craftStartDate), 'YYYY-MM-DD') }}</span>
          </td>
          <td>结束日期</td>
          <td>
            <span v-if="!planData.craftEndDate">&nbsp;</span>
            <span v-else style="min-width: 70px;">{{ formatDate(new Date(planData.craftEndDate), 'YYYY-MM-DD') }}</span>
          </td>
          <td>负责人</td>
          <td colspan="2">{{ userInit.find((user) => user.id == planData.craftOwner)?.nickname }}</td>
        </tr>

        </tbody>

        <tbody>
        <tr>
          <td colspan="10" style="height: 30px">
            <div style="text-align: left; width: 100%">子项目信息:</div>
          </td>
        </tr>
        <tr>
          <td class="xh"> 序号 </td>
          <td colspan="3"> 名称/编号 </td>
          <td> 设备型号 </td>
          <td> 数量 </td>
          <td> 主要材料 </td>
          <td style="width:120px"> 毛坯日期 </td>
          <td> 2D/日期 </td>
          <td> 3D/日期 </td>
        </tr>
        <tr v-for="(item,idx) in formData.projectOrderSubs.slice(0, 6)" :key="idx">
          <td class="xh"> {{ idx+1 }} </td>
          <td colspan="3" style="padding: 0 0">
            <div style="display: flex; flex-direction: column; justify-content: space-between">
              <span> {{item.name}} </span>
<!--              <span style="border-bottom: 1px solid #666"> {{item.name}} </span>-->
<!--              <span v-if="!item.projectSubShortName">&nbsp;</span>-->
<!--              <span v-else style="font-size: 10px">{{ formData.code+'-'+formData.customer.code+'-'+ item.projectSubShortName}}</span>-->
            </div>
          </td>
          <td>{{equipInit.find((equip) => equip.id == item.equipId)?.name}} </td>
          <td>{{item.amount}} </td>
          <td>{{ item.compositionName }} </td>
          <td>
            <span v-if="!item.blankDate"> &nbsp;</span>
            <span v-else>{{ formatDate(new Date(item.blankDate), 'YYYY-MM-DD') }} </span>
          </td>
          <td style="padding: 0 0">
            <div style="display: flex; flex-direction: column; justify-content: space-between;width: 100px">
              <span v-if="!item.twoDimDate" style="border-bottom: 1px solid #666">&nbsp;</span>
              <span v-else style="border-bottom: 1px solid #666"> {{ formatDate(new Date(item.twoDimDate), 'YYYY-MM-DD') }} </span>
              <span v-if="userInit.find((user) => user.id === item.twoDimOwner)?.nickname">{{ userInit.find((user) => user.id == item.twoDimOwner)?.nickname }}</span>
              <span v-else>&nbsp;</span>
            </div>
          </td>
          <td style="padding: 0 0">
            <div style="display: flex; flex-direction: column; justify-content: space-between;width: 100px">
              <span v-if="!item.threeDimDate" style="border-bottom: 1px solid #666">&nbsp;</span>

              <span v-else style="border-bottom: 1px solid #666"> {{ formatDate(new Date(item.threeDimDate), 'YYYY-MM-DD') }} </span>
              <span v-if="userInit.find((user) => user.id === item.threeDimOwner)?.nickname">
                  {{ userInit.find((user) => user.id === item.threeDimOwner)?.nickname }}
                </span>
              <span v-else>&nbsp;</span>
            </div>
          </td>
        </tr>
        </tbody>

        <tbody v-if="formData.projectOrderSubs.length<6">
        <tr v-for="item in (6-formData.projectOrderSubs.length)" :key="item">
          <td> {{item+(formData.projectOrderSubs.length)}}</td>
          <td colspan="3">&nbsp; </td>
          <td> &nbsp; </td>
          <td> &nbsp; </td>
          <td>&nbsp; </td>
          <td> &nbsp; </td>
          <td> &nbsp; </td>
          <td>&nbsp; </td>
        </tr>
        </tbody>
        <tbody class="masterClass">

        <tr>
          <td class="xh"> 序号 </td>
          <td colspan="2" style="width: 200px"> 工艺流程 </td>
          <td colspan="2"> 开始日期 </td>
          <td colspan="2"> 结束日期 </td>
          <td> 责任人 </td>
          <td colspan="2"> 备注 </td>
        </tr>
        <tr v-for="(its,index) in planData.craftInfos" :key="its.index">
          <td class="xh"> {{ index+1 }} </td>
          <td colspan="2"> {{ its.name }}</td>

          <td colspan="2">
            <span v-if="!its.startDate"> &nbsp;</span>
            <span v-else>{{formatDate(new Date(its.startDate), 'YYYY-MM-DD')}}</span>
          </td>
          <td colspan="2">
            <span v-if="!its.endDate">&nbsp;</span>
            <span v-else style="min-width: 70px;">{{formatDate(new Date(its.endDate), 'YYYY-MM-DD')}} </span>
          </td>
          <td>{{userInit.find((user) => user.id == its.owner)?.nickname}} </td>
          <td colspan="2"> {{its.description}}</td>
        </tr>
        </tbody>
        <tbody>
        <tr>
          <td colspan="10">
            <div
style="
                  text-align: left;
                  width: 100%;
                  display: flex;
                  flex-direction: column;
                  padding-left: 15px;
                ">
              <span>说明:</span>
              <span>1.每个项目的零部件制作工艺，材料材质，硬度要求必须统一，出现任何问题，各工程师负责!</span>
              <span>2.模具调试，试模需要根据客户要求，自己安排调试，我司根据需要安排人员参与配合。</span>
            </div>
          </td>
        </tr>
        </tbody>
        <tbody class="masterClass">
        <tr>
          <td colspan="4" style="width: 33%"> 编制/日期 </td>
          <td colspan="3" style="width: 33%"> 审核/日期 </td>
          <td colspan="3" style="width: 33%"> 批准/日期 </td>
        </tr>

        <tr>
          <td colspan="4">
            <span v-if="!planData.editorDate"> &nbsp;</span>
            <span v-else>{{formatDate(new Date(planData.editorDate), 'YYYY-MM-DD')}}</span>
          </td>
          <td colspan="3">
            <span v-if="!planData.auditDate"> &nbsp;</span>
            <span v-else>{{formatDate(new Date(planData.auditDate), 'YYYY-MM-DD')}}</span>
          </td>
          <td colspan="3">
            <span v-if="!planData.approveDate"> &nbsp;</span>
            <span v-else>{{formatDate(new Date(planData.approveDate), 'YYYY-MM-DD')}}</span>
          </td>
        </tr>
        <tr>
          <td colspan="4">
            <span v-if="!planData.editor"> &nbsp;</span>
            <span v-else> {{ userInit.find((user) => user.id == planData.editor)?.nickname }}</span>
          </td>
          <td colspan="3">
            <span v-if="!planData.auditor"> &nbsp;</span>
            <span v-else> {{ userInit.find((user) => user.id == planData.auditor)?.nickname }}</span>

          </td>
          <td colspan="3">
            <span v-if="!planData.approver"> &nbsp;</span>
            <span v-else> {{ userInit.find((user) => user.id == planData.approver)?.nickname }}</span>
          </td>
        </tr>
        </tbody>
      </table>

      <div v-if="formData.projectOrderSubs.length>6">
        <!-- 附页是否开启需要判断 根据子项目信息-->
        <table border="2" cellspacing="0" id="table" style="height:27.2cm;">
<!--          <tbody >-->
<!--          <tr>-->
<!--            <td colspan="2">-->
<!--              <div style="width: 100px; text-align: center">-->
<!--                <img :src="logoDataUrl" style="width: 100%" alt="" />-->
<!--              </div>-->
<!--            </td>-->
<!--            <td colspan="6">-->
<!--              <span style="font-size: 20px; font-weight: 700">模具生产计划单-附页</span>-->
<!--            </td>-->
<!--            <td colspan="2" style="padding: 5px 0">-->
<!--              <div style="border-bottom: 1px solid #666; padding-bottom: 5px;font-size: 16px">项目编号</div>-->
<!--              <div style="padding-top: 5px; font-size: 16px">{{ formData.code }}</div>-->
<!--            </td>-->
<!--          </tr>-->
<!--          </tbody>-->
<!--          <tbody class="masterClass">-->
<!--          <tr>-->
<!--            <td colspan="2" style="font-size: 16px"> 客户名称 </td>-->
<!--            <td colspan="5" style="font-size: 16px">-->
<!--              <span>{{ formData.customerName }}</span>-->
<!--            </td>-->
<!--            <td colspan="1" style="font-size: 16px">{{ formData.customer.brief }}</td>-->
<!--            <td style="font-size: 16px"> 编码： </td>-->
<!--            <td style="font-size: 16px">{{ formData.customer.code }} </td>-->
<!--          </tr>-->
<!--          </tbody>-->
<!--          <tr class="masterClass">-->
<!--            <td colspan="2" style="font-size: 16px"> 项目名称 </td>-->
<!--            <td colspan="6" style="font-size: 16px">-->
<!--              {{ formData.projectName }}-->
<!--            </td>-->
<!--            <td style="font-size: 16px"> 业务员： </td>-->
<!--            <td>{{ formData.businessManName }} </td>-->
<!--          </tr>-->
<!--          <tr class="masterClass">-->
<!--            <td colspan="2" style="font-size: 16px"> 项目工期 </td>-->
<!--            <td  colspan="1" style="padding: 0 5px"> 起 </td>-->
<!--            <td colspan="1" style="min-width: 70px;">-->
<!--             {{ formatDate(new Date(formData.projectStartTime), 'YYYY-MM-DD') }}-->
<!--            </td>-->
<!--            <td colspan="1">至</td>-->
<!--            <td colspan="1" style="min-width: 70px;">{{ formatDate(new Date(formData.projectEndTime), 'YYYY-MM-DD') }}</td>-->
<!--            <td style="min-width: 70px;">天数</td>-->
<!--            <td colspan="1">{{ betweenDay(new Date(formData.projectStartTime), new Date(formData.projectEndTime))+1 }}</td>-->
<!--            <td colspan="1"> 是否有价格： </td>-->
<!--            <td colspan="1">{{ getDictLabel(DICT_TYPE.HELI_COMMON_IS_OR_NOT, formData.hasPrice) }} </td>-->
<!--          </tr>-->
<!--          <tr class="masterClass">-->
<!--            <td colspan="10">-->
<!--              <div style="font-size: 10px; height: 30px; line-height: 30px">-->
<!--                <span>接上页</span>-->
<!--              </div>-->
<!--            </td>-->
<!--          </tr>-->

          <tbody >
          <tr>
            <td colspan="10" style="height: 30px">
              <div style="text-align: left; width: 100%">子项目信息:</div>
            </td>
          </tr>
          <tr>
            <td class="xh" style="width: 20%" > 序号 </td>
            <td colspan="3" style="width: 25%"> 名称/编号 </td>
            <td style="width: 10%"> 设备型号 </td>
            <td style="width: 10%"> 数量 </td>
            <td style="width: 10%"> 主要材料 </td>
            <td style="width: 10%"> 毛坯日期 </td>
            <td style="width: 10%"> 2D/日期 </td>
            <td style="width: 10%"> 3D/日期 </td>
          </tr>
          </tbody>
          <tbody>
<!--          <tr v-for="(item, idx) in formData.projectOrderSubs.slice(6)" :key="idx">-->
<!--            <td class="xh"> {{ idx+7 }} </td>-->
<!--            <td colspan="3" style="padding: 0 0">-->
<!--              <div style="display: flex; flex-direction: column; justify-content: space-between">-->
<!--                <span > {{item.name}} </span>-->
<!--&lt;!&ndash;                <span style="border-bottom: 1px solid #666"> {{item.name}} </span>&ndash;&gt;-->
<!--&lt;!&ndash;                <span v-if="!item.projectSubShortName">&nbsp;</span>&ndash;&gt;-->
<!--&lt;!&ndash;                <span v-else style="font-size: 10px">{{ formData.code+'-'+formData.customer.code+'-'+ item.projectSubShortName}}</span>&ndash;&gt;-->
<!--              </div>-->
<!--            </td>-->
<!--            <td>{{equipInit.find((equip) => equip.id == item.equipId)?.name}} </td>-->
<!--            <td>{{item.amount}} </td>-->
<!--            <td>{{ item.compositionName }} </td>-->
<!--            <td>-->
<!--              <span v-if="!item.blankDate"> &nbsp;</span>-->
<!--              <span v-else>{{ formatDate(new Date(item.blankDate), 'YYYY-MM-DD') }} </span>-->
<!--            </td>-->
<!--            <td style="padding: 0 0">-->
<!--              <div style="display: flex; flex-direction: column; justify-content: space-between;width: 80px">-->
<!--                <span v-if="!item.twoDimDate" style="border-bottom: 1px solid #666">&nbsp;</span>-->
<!--                <span v-else style="border-bottom: 1px solid #666"> {{ formatDate(new Date(item.twoDimDate), 'YYYY-MM-DD') }} </span>-->
<!--                <span v-if="userInit.find((user) => user.id === item.twoDimOwner)?.nickname">{{ userInit.find((user) => user.id == item.twoDimOwner)?.nickname }}</span>-->
<!--                <span v-else>&nbsp;</span>-->
<!--              </div>-->
<!--            </td>-->
<!--            <td style="padding: 0 0">-->
<!--              <div style="display: flex; flex-direction: column; justify-content: space-between;width: 80px">-->
<!--                <span v-if="!item.threeDimDate" style="border-bottom: 1px solid #666">&nbsp;</span>-->

<!--                <span v-else style="border-bottom: 1px solid #666"> {{ formatDate(new Date(item.threeDimDate), 'YYYY-MM-DD') }} </span>-->
<!--                <span v-if="userInit.find((user) => user.id === item.threeDimOwner)?.nickname">-->
<!--                    {{ userInit.find((user) => user.id === item.threeDimOwner)?.nickname }}-->
<!--                  </span>-->
<!--                <span v-else>&nbsp;</span>-->
<!--              </div>-->
<!--            </td>-->
<!--          </tr>-->
<tr v-for="(item,idx) in formData.projectOrderSubs.slice(6)" :key="idx" >
  <td class="xh"> {{ idx+7 }} </td>
  <td colspan="3" style="padding: 0 0">
    <div style="display: flex; flex-direction: column; justify-content: space-between">
      <span> {{item.name}} </span>
      <!--              <span style="border-bottom: 1px solid #666"> {{item.name}} </span>-->
      <!--              <span v-if="!item.projectSubShortName">&nbsp;</span>-->
      <!--              <span v-else style="font-size: 10px">{{ formData.code+'-'+formData.customer.code+'-'+ item.projectSubShortName}}</span>-->
    </div>
  </td>
  <td>{{equipInit.find((equip) => equip.id == item.equipId)?.name}} </td>
  <td>{{item.amount}} </td>
  <td>{{ item.compositionName }} </td>
  <td>
    <span v-if="!item.blankDate"> &nbsp;</span>
    <span v-else>{{ formatDate(new Date(item.blankDate), 'YYYY-MM-DD') }} </span>
  </td>
  <td style="padding: 0 0">
    <div style="display: flex; flex-direction: column; justify-content: space-between;width: 100px">
      <span v-if="!item.twoDimDate" style="border-bottom: 1px solid #666">&nbsp;</span>
      <span v-else style="border-bottom: 1px solid #666"> {{ formatDate(new Date(item.twoDimDate), 'YYYY-MM-DD') }} </span>
      <span v-if="userInit.find((user) => user.id === item.twoDimOwner)?.nickname">{{ userInit.find((user) => user.id == item.twoDimOwner)?.nickname }}</span>
      <span v-else>&nbsp;</span>
    </div>
  </td>
  <td style="padding: 0 0">
    <div style="display: flex; flex-direction: column; justify-content: space-between;width: 100px">
      <span v-if="!item.threeDimDate" style="border-bottom: 1px solid #666">&nbsp;</span>

      <span v-else style="border-bottom: 1px solid #666"> {{ formatDate(new Date(item.threeDimDate), 'YYYY-MM-DD') }} </span>
      <span v-if="userInit.find((user) => user.id === item.threeDimOwner)?.nickname">
                  {{ userInit.find((user) => user.id === item.threeDimOwner)?.nickname }}
                </span>
      <span v-else>&nbsp;</span>
    </div>
  </td>
</tr>
          </tbody>
          <tbody>
          <tr v-for="item in num" :key="item">
            <td> {{item+(formData.projectOrderSubs.length)}}</td>
            <td colspan="3">&nbsp; </td>
            <td> &nbsp; </td>
            <td> &nbsp; </td>
            <td>&nbsp; </td>
            <td> &nbsp; </td>
            <td> &nbsp; </td>
            <td>&nbsp; </td>
          </tr>
          </tbody>

<!--          <tbody>-->
<!--          <tr>-->
<!--            <td colspan="10">-->
<!--              <div-->
<!--style="-->

<!--                  text-align: left;-->
<!--                  width: 100%;-->
<!--                  display: flex;-->
<!--                  flex-direction: column;-->
<!--                  padding-left: 15px;-->
<!--                ">-->
<!--                <span>说明:</span>-->
<!--                <span>1.每个项目的零部件制作工艺，材料材质，硬度要求必须统一，出现任何问题，各工程师负责!</span>-->
<!--                <span>2.模具调试，试模需要根据客户要求，自己安排调试，我司根据需要安排人员参与配合。</span>-->
<!--              </div>-->
<!--            </td>-->
<!--          </tr>-->
<!--          </tbody>-->
<!--          <tbody class="masterClass">-->
<!--          <tr>-->
<!--            <td colspan="4" style="width: 33%"> 编制/日期 </td>-->
<!--            <td colspan="3" style="width: 33%"> 审核/日期 </td>-->
<!--            <td colspan="3" style="width: 33%"> 批准/日期 </td>-->
<!--          </tr>-->

<!--          <tr>-->
<!--            <td colspan="4">-->
<!--              <span v-if="!planData.editorDate"> &nbsp;</span>-->
<!--              <span v-else>{{formatDate(new Date(planData.editorDate), 'YYYY-MM-DD')}}</span>-->
<!--            </td>-->
<!--            <td colspan="3">-->
<!--              <span v-if="!planData.auditDate"> &nbsp;</span>-->
<!--              <span v-else>{{formatDate(new Date(planData.auditDate), 'YYYY-MM-DD')}}</span>-->
<!--            </td>-->
<!--            <td colspan="3">-->
<!--              <span v-if="!planData.approveDate"> &nbsp;</span>-->
<!--              <span v-else>{{formatDate(new Date(planData.approveDate), 'YYYY-MM-DD')}}</span>-->
<!--            </td>-->
<!--          </tr>-->
<!--          <tr>-->
<!--            <td colspan="4">-->
<!--              <span v-if="!planData.editor"> &nbsp;</span>-->
<!--              <span v-else> {{ userInit.find((user) => user.id == planData.editor)?.nickname }}</span>-->
<!--            </td>-->
<!--            <td colspan="3">-->
<!--              <span v-if="!planData.auditor"> &nbsp;</span>-->
<!--              <span v-else> {{ userInit.find((user) => user.id == planData.auditor)?.nickname }}</span>-->

<!--            </td>-->
<!--            <td colspan="3">-->
<!--              <span v-if="!planData.approver"> &nbsp;</span>-->
<!--              <span v-else> {{ userInit.find((user) => user.id == planData.approver)?.nickname }}</span>-->
<!--            </td>-->
<!--          </tr>-->
<!--          </tbody>-->
        </table>
      </div>
    </div>
    <template #footer>
      <!-- 【打印】 -->
      <el-button @click="onPrint" type="primary">打印</el-button>
      <el-button @click="outopen">取消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
// import { ref, reactive } from 'vue'
import * as EquipApi from '@/api/heli/equip'
import * as UserApi from '@/api/system/user'
import * as PlanApi from '@/api/heli/plan'
import * as PlanSubApi from '@/api/heli/plansub'
import * as ProjectOrderApi from '@/api/heli/projectorder'
import { getIntDictOptions,  DICT_TYPE, getDictLabel } from '@/utils/dict'
import { betweenDay,  formatDate } from '@/utils/formatTime'
import { getCustomer } from '@/api/heli/customer'
import { getOperateLogPage } from '@/api/system/operatelog'
import urlimg from '@/assets/imgs/exlogo.png'
const logoDataUrl = ref('') // 存储Logo的Base64编码数据URL
const dialogVisible = ref(false) // 弹窗的是否展示
const num = ref(0) // 存储Logo的Base64编码数据URL

const onPrint = () => {
  // 拿到打印页面dom节点
  const printNode = document.querySelector('.print-wrap')
  if (!printNode) return
  // 页面文档创建一个空的内框架，用于挂载打印节点，并设置一定的样式
  const newIframe: any = document.createElement('iframe')
  newIframe.setAttribute(
    'style',
    'width:0px;height:0px;position:absolute;left:-9999px;top:-9999px;'
  )
  newIframe.setAttribute('align', 'center')
  document.body.appendChild(newIframe)
  // 将打印页面设置为内框架内容
  let doc: any = null
  doc = newIframe.contentWindow.document
  doc.write(`
<style type="text/css">
      /* 浏览器打印基本样式 */
    .page {
      width: 21cm;
      min-height: 29.7cm;
      padding: 10mm;
      margin: 20px auto;
      border: 1px #d3d3d3 solid;
      border-radius: 5px;
      background: white;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
      position: relative;
      font-size: 12px !important;
    }

    @page {
      size: A4;
      margin:0.8cm 1cm 1.4cm 1cm;;
    }
    @media print {
      .page {
        margin: 10mm;
        border: initial;
        border-radius: initial;
        width: initial;
        min-height: initial;
        box-shadow: initial;
        background: initial;
        page-break-after: always;
      }
    }
    /* 注册页脚为运行元素 */
.footer {
  position: running(footer);
  text-align: right;
  font-size: 10px;
  color: #666;
  border-top: 1px dashed #ccc;
  padding-top: 2px;
}

/* 定义页脚位置 */
@page {
  @bottom-right {
    content:   counter(page) "/" counter(pages);
    font-family: Arial; /* 防止继承奇怪字体 */
  }
}

    table {
      width: 100%; /* 让表格宽度100%占满其父元素宽度 */
      height: auto; /* 高度根据内容自适应 */
      font-size: 12px;
      text-align: center;
      border-collapse: collapse;
      margin-top: 5mm; /* 添加顶部外边距，替代原先的页内边距 */
      tr{
        td {
        padding: 5px 0;
        border: 1px solid #333;
      }
      }
    }
    .masterClass {
      height: 15px;
    }
    .xh {
      width: 50px !important;
    }
    .xh {
        height: 20px !important;
}
    .checkbox {
      border: 2px solid #999;
      width: 10px;
      height: 10px;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left:10px ;
    }
    </style>
    <div>
      ${printNode.innerHTML}

    </div>`)
  doc.close()
  // 浏览器打印页面打开渲染
  setTimeout(() => {
    newIframe.contentWindow.focus()
    newIframe.contentWindow.print()
    document.body.removeChild(newIframe) // 移除打印内框架，下次打印下次再挂载
    dialogVisible.value = false
  }, 100)

}
// const onPrint = () => {
//   const printNode = document.querySelector('.print-wrap');
//   if (!printNode) return;
//
//   // 克隆节点避免污染原始DOM
//   const printClone = printNode.cloneNode(true) as HTMLElement;
//   const pages = printClone.querySelectorAll('.page');
//   const totalPages = pages.length;
//   console.log(totalPages)
//   // 动态添加页码元素
//   let currentPage = 1;
//   pages.forEach(page => {
//     const pageNum = document.createElement('div');
//     pageNum.className = 'page-footer';
//     pageNum.innerHTML = `<span class="page-number">${currentPage}/${totalPages}</span>`;
//
//     // 插入页码到页面底部
//     const footer = document.createElement('div');
//     footer.className = 'print-footer';
//     footer.appendChild(pageNum);
//     page.appendChild(footer);
//     currentPage++;
//   });
//   // 创建打印专用iframe
//   const newIframe = document.createElement('iframe');
//   Object.assign(newIframe.style, {
//     width: '0px',
//     height: '0px',
//     position: 'absolute',
//     left: '-9999px',
//     top: '-9999px'
//   });
//   document.body.appendChild(newIframe);
//
//   const doc = newIframe.contentWindow!.document!;
//   doc.write(`
//     <style>
//       /* 保留原有样式 */
//       .page {
//         width: 21cm;
//         min-height: 29.7cm;
//         padding: 10mm;
//         margin: 20px auto;
//         border: 1px #d3d3d3 solid;
//         border-radius: 5px;
//         background: white;
//         box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
//         position: relative;
//         font-size: 12px !important;
//       }
//
//       @page {
//         size: A4;
//         margin: 1cm;
//       }
//
//       @media print {
//         .page {
//           margin: 10mm;
//           border: initial;
//           border-radius: initial;
//           width: initial;
//           min-height: initial;
//           box-shadow: initial;
//           background: initial;
//           page-break-after: always;
//         }
//       }
//
//       /* 新增页码样式 */
//       .print-footer {
//         position: absolute;
//         bottom: 5mm;
//         right: 5mm;
//         font-size: 10px;
//         color: #666;
//       }
//
//       .page-number {
//         padding: 2px 6px;
//         border: 1px solid #ddd;
//         border-radius: 3px;
//         background: #f8f8f8;
//       }
//      table {
//        width: 100%; /* 让表格宽度100%占满其父元素宽度 */
//        height: auto; /* 高度根据内容自适应 */
//        font-size: 12px;
//        text-align: center;
//        border-collapse: collapse;
//        margin-top: 5mm; /* 添加顶部外边距，替代原先的页内边距 */
//        tr{
//          td {
//          padding: 5px 0;
//          border: 1px solid #333;
//        }
//        }
//      }
//      .masterClass {
//        height: 15px;
//      }
//      .xh {
//        width: 50px !important;
//      }
//      .xh {
//          height: 20px !important;
//  }
//      .checkbox {
//        border: 2px solid #999;
//        width: 10px;
//        height: 10px;
//        display: flex;
//        justify-content: center;
//        align-items: center;
//        margin-left:10px ;
//      }
//
//     </style>
//     <div>${printClone.innerHTML}</div>
//   `);
//   doc.close();
//
//   // 打印处理
//   setTimeout(() => {
//     newIframe.contentWindow!.focus();
//     newIframe.contentWindow!.print();
//
//     // 打印后清理
//     document.body.removeChild(newIframe);
//     dialogVisible.value = false;
//
//     // 恢复原始内容（可选）
//     // printNode.innerHTML = originalContent;
//   }, 300);
// };
const outopen = () => {
  dialogVisible.value = false
}

const formData = ref({
  id: undefined,
  code: undefined,
  orderStatus: 4,
  deliveryStatus: 1,
  businessDeptId: undefined,
  customerId: undefined,
  projectName: undefined,
  businessLine: undefined,
  blueprintNo: undefined,
  hasPrice: 1,
  price: undefined,
  currency: '1',
  projectStartTime: undefined,
  projectEndTime: undefined,
  isUrgency: 0,
  property: 1,
  referenceTechnology: undefined,
  hasAlter: 0,
  lastAlterTime: undefined,
  qualityRequirement: undefined,
  remark: undefined,
  hasContract: 0,
  hasTechnologyProtocol: 0,
  hasBlueprint: 0,
  blueprintRemark: undefined,
  status: 1,
  businessMan: undefined,
  createTime: new Date(),
  projectOrderSubs: [],
  attachments: [],
  operateLogs: [],
  contractNo: undefined,
  active: '',
  activeOpinion: '',
  isSnapshot: 0,
  snapshotId: undefined,
  snapshotCode: undefined,
  orderTime: new Date(),
  snapshotOrderTime: undefined,
  alterFieldNames: [],
  customer: {},
  creatorName: undefined,
  auditTime: undefined,
  auditUserName: undefined,
  approveTime: undefined,
  approveUserName: undefined
})
const planData = ref({
  id: undefined,
  projectId: undefined,
  projectOwner: undefined,
  hasCraft: undefined,
  craftOwner: undefined,
  craftStartTime: undefined,
  craftEndTime: undefined,
  editor: undefined,
  editorDate: undefined,
  auditor: undefined,
  auditDate: undefined,
  approver: undefined,
  approveDate: undefined,
  description: undefined,
  status: undefined,
  createTime: undefined,
  operateLogs: [],
  projectOrderSubs: [],
  projectPlanSubs: [],
  craftInfos: [],
  craftContent: undefined
})
const userInit = ref()
const equipInit = ref()
/** 打开弹窗 */
const open = async (id: number) => {
  // 设备信息下拉列表数据
  equipInit.value = await EquipApi.getSimpList()
  //用户列表数据
  userInit.value = await UserApi.getSimpleUserList()
  //图片处理
  // 在组件挂载后，将Logo图片转换为Base64编码数据URL
  const logoImage = new Image()
  logoImage.src = urlimg // 替换为Logo图片路径
  logoImage.onload = () => {
    const canvas = document.createElement('canvas')
    canvas.width = logoImage.width
    canvas.height = logoImage.height
    const context = canvas.getContext('2d')
    context.drawImage(logoImage, 0, 0)
    const base64String = canvas.toDataURL('image/png')
    logoDataUrl.value = base64String
  }

  dialogVisible.value = true
  resetForm()
  // 生产计划数据
  planData.value = await PlanApi.getPlan(id)

  formData.value = await ProjectOrderApi.getProjectOrder(planData.value.projectId)
  // 子项列表
  formData.value.projectOrderSubs = await ProjectOrderApi.getProjectOrderSubListByProjectOrderId(
    planData.value.projectId
  )
  // 生产计划子项目数据
  await handleInitPlanSub(id)
  // 生产计划工艺数据
  await handleCraftInfo()
  formData.value.customer = await getCustomer(formData.value.customerId)
  // 操作日志查询 并筛选审核/批准信息
  let logParams = {
    pageNo: 1,
    pageSize: 2,
    typeList: [9, 10]
  }
  const logs = await getOperateLogPage(logParams)
  if (logs.list && logs.list.length == 2) {
    const approveLog = logs.list[0]
    const auditLog = logs.list[1]
    formData.value.approveTime = approveLog.startTime
    formData.value.approveUserName = approveLog.userNickname
    formData.value.auditTime = auditLog.startTime
    formData.value.auditUserName = auditLog.userNickname
  }
  if (formData.value.projectOrderSubs.length>6){
    if (formData.value.projectOrderSubs.length>33){
      var number = formData.value.projectOrderSubs.length-33;
      const remainder = number % 29;
      const emptyRows = remainder === 0 ? 0 : 29 - remainder;
      num.value=emptyRows
      console.log(num.value)
    }else {
      var number = formData.value.projectOrderSubs.length-6;
      const remainder = number % 27;
      const emptyRows = remainder === 0 ? 0 : 27 - remainder;
      num.value=emptyRows
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const handleCraftInfo = async () => {
  if (planData.value.craftContent == null) {
    planData.value.craftInfos = []

    getIntDictOptions(DICT_TYPE.HELI_CRAFT).forEach((dict) => {
      planData.value.craftInfos.push({
        id: dict.value,
        name: dict.label,
        startDate: '',
        endDate: '',
        owner: '',
        description: ''
      })
    })
  } else {
    planData.value.craftInfos = eval(planData.value.craftContent)
  }
}
const handleInitPlanSub = async (id) => {
  // 生产计划子项列表
  const queryParams = reactive({
    pageNo: 1,
    pageSize: 99,
    projectPlanId: id
  })

  planData.value.projectPlanSubs = (await PlanSubApi.getPlanSubPage(queryParams)).list

  formData.value.projectOrderSubs.forEach((item) => {
    if (planData.value.projectPlanSubs.filter((sub) => sub.projectSubId == item.id).length > 0) {
      var subTemp = planData.value.projectPlanSubs.find((sub) => sub.projectSubId == item.id)
      item.planSubId = subTemp.id
      item.projectPlanId = subTemp.projectPlanId
      item.projectId = subTemp.projectId
      item.projectSubId = subTemp.projectSubId
      item.projectSubShortName = subTemp.projectSubShortName
      item.projectSubCode = subTemp.projectSubCode
      item.mouldId = subTemp.mouldId
      item.equipId = subTemp.equipId
      item.blankDate = subTemp.blankDate
      item.blankOwner = subTemp.blankOwner
      item.twoDimDate = subTemp.twoDimDate
      item.twoDimOwner = subTemp.twoDimOwner
      item.threeDimDate = subTemp.threeDimDate
      item.threeDimOwner = subTemp.threeDimOwner
    }
  })
}
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    orderStatus: 4,
    deliveryStatus: 1,
    businessDeptId: undefined,
    customerId: undefined,
    projectName: undefined,
    businessLine: undefined,
    blueprintNo: undefined,
    hasPrice: 1,
    price: undefined,
    currency: '1',
    projectStartTime: undefined,
    projectEndTime: undefined,
    isUrgency: 0,
    property: 1,
    referenceTechnology: undefined,
    hasAlter: 0,
    lastAlterTime: undefined,
    qualityRequirement: undefined,
    remark: undefined,
    hasContract: 0,
    hasTechnologyProtocol: 0,
    hasBlueprint: 0,
    blueprintRemark: undefined,
    status: 1,
    businessMan: undefined,
    createTime: new Date(),
    projectOrderSubs: [],
    attachments: [],
    operateLogs: [],
    contractNo: undefined,
    active: '',
    activeOpinion: '',
    isSnapshot: 0,
    snapshotId: undefined,
    snapshotCode: undefined,
    orderTime: new Date(),
    snapshotOrderTime: undefined,
    alterFieldNames: [],
    customer: {},
    creatorName: undefined,
    auditTime: undefined,
    auditUserName: undefined,
    approveTime: undefined,
    approveUserName: undefined
  }
}
</script>

<style scoped lang="scss">
.page {
  width: 22cm;
  min-height: 29.7cm;
  padding: 10mm;
  margin: 20px auto;
  border: 1px #d3d3d3 solid;
  border-radius: 5px;
  background: white;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  position: relative;
  font-size: 1px !important;
}

@page {
  size: A4;
  margin: 0;
}
@media print {
  .page {
    margin: 0;
    border: initial;
    border-radius: initial;
    width: initial;
    min-height: initial;
    box-shadow: initial;
    background: initial;
    page-break-after: always;
  }
}
.footer {
  position: running(footer);
  text-align: right;
  font-size: 10px;
  color: #666;
  border-top: 1px dashed #ccc;
  padding-top: 5px;
}

/* 定义页脚位置 */
@page {
  @bottom-right {
    content:   counter(page) "/" counter(pages);
    font-family: Arial; /* 防止继承奇怪字体 */
  }
}
table {
  width: 100%; /* 让表格宽度100%占满其父元素宽度 */
  height: auto; /* 高度根据内容自适应 */
  font-size: 10px;
  text-align: center;
  border-collapse: collapse;
  margin-top: 5mm; /* 添加顶部外边距，替代原先的页内边距 */
  tr {
    td {
      padding: 2px 0;
      border: 1px solid #333;
    }
  }
}
.xh {
  width: 40px !important;
}
.xhs {
  height: 20px !important;
}
.checkbox {
  border: 2px solid #999;
  width: 15px;
  height: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-left: 10px;
}
.masterClass {
  height: 15px;
}
/*
	A4的大小：21cm*29.7cm（width:794px;）。
	单位换算：1 inch = 2.54 cm 1mm = 96 px 1 cm = 37.79528 px*/
</style>
