<template>
  <div class="page-body">

    <div class="printcard-container">
      <div :class="item.isSelected ? 'printcard printcard-selected' : 'printcard'"
        v-for="(item, index) in InkjetPrinterData" :key="index" @click="toggleCard(item)">
        <!-- 卡片内容 -->
        <div class="printcard-content">
          <div class="printcard-header">
            <div class="printcard-title">
              <h4> {{ item.name }}</h4>
            </div>
            <div class="printcard-buttons">
              <a-button type="primary" @click.stop="pageStart(item)">启动</a-button>
              <a-button type="danger" @click.stop="pageStop(item)" style=" margin-left: 5px; ">停止</a-button>

            </div>
          </div>
          <h3> {{ (item.ip || '') + (item.ip ? ":" : '') + (item.port || '') }}</h3>
          <div class="printcard-toolbar">
            <a-icon key="setting" type="setting" @click.stop="pageSetting(item)"></a-icon>
          </div>
        </div>
      </div>
    </div>

    <div style="margin: 10px;">
      <vxe-form :data="searchFormData" :items="searchFormItems" titleColon @submit="onSearch">
        <template #date="{ }">
          <a-form-item label="单据时间" :style="{ display: 'inline-block', width: 120 }">
          </a-form-item>
          <a-form-item :style="{ display: 'inline-block', width: 'calc(100% - 120px )' }">
            <a-range-picker @change="onDateChange" />
          </a-form-item>
        </template>
      </vxe-form>

      <vxe-table border show-overflow keep-source ref="xTable" :height="table1Height" :data="detailsData"
        :span-method="rowspanMethod" :column-config="{ resizable: true }">



        <vxe-column field="voucherdate" title="单据日期" width="110"></vxe-column>
        <vxe-column field="vouchercode" title="单据号" width="140"></vxe-column>
        <vxe-column field="departmentName" title="生产车间" width="120"></vxe-column>
        <vxe-column field="inventoryName" title="存货名称" width="130"></vxe-column>
        <vxe-column field="quantity" title="数量" width="80"></vxe-column>

        <vxe-column title="操作" width="230">
          <template #default="{ row }">
            <a-button type="primary" @click.stop="pageShowSend(row)" :disabled="isDisabled1(row)">开工</a-button>
            <a-button type="primary" @click.stop="print(row)" style="margin-left: 2px;"
              :disabled="isDisabled2(row)">打印</a-button>
            <a-button type="primary" @click.stop="pageShowDone(row)" style="margin-left: 2px;"
              :disabled="isDisabled2(row)">完工</a-button>
          </template>
        </vxe-column>


      </vxe-table>

    </div>



  </div>
</template>

<script>
import BASE_URL from '@/services/base/api.js';
import printSetting from '../basic/print.js';
import { toDateString } from 'xe-utils'

export default {

  props: {
    dataId: {
    }

  },

  data() {

    // 页面数据变量
    var pageData = {

      actions: {
        get: `${BASE_URL.BASE_URL}/InkjetPrinter/v1/inkjet/printer/list`,
        getSqDepartments: `http://36.133.149.247:9112/api/tp/getSqDepartments`,
        sequanceData: `http://36.133.149.247:9112/api/tp/getSqListV3`
      },

      start_time: 0, // 开始时间
      end_time: 0, // 结束时间 
      //搜索区
      searchFormData: {
        vouchercode: '',
        inventoryName: '',
        departmentName: ''
      },
      // 搜索区配置
      searchRules: [
        { key: "vouchercode", mode: "like" },
        { key: "inventoryName", mode: "like" },
        { key: "departmentName", mode: "equal" },

      ],
      //搜索区
      searchFormItems: [ // 子项

        {
          span: 24, children: [
            { span: 6, slots: { default: 'date' } },  // 自定义列
            { field: 'vouchercode', title: '单据编号', span: 6, itemRender: { name: '$input', props: { placeholder: '请输入单据编号' } } },
            { field: 'inventoryName', title: '存货名称', span: 6, itemRender: { name: '$input', props: { placeholder: '请输入存货名称' } } },
          ]
        },
        {
          span: 24,
          children: [
            { field: 'departmentName', title: '生产车间', span: 12, itemRender: { name: '$select', props: { placeholder: '请输入生产车间', options: [] } } },

            {
              align: 'right', span: 6, itemRender: {  // 按钮列
                name: '$buttons', children: [{ props: { type: 'submit', content: '搜索', status: 'primary' } },  // 搜索按钮
                { props: { type: 'reset', content: '重置' } }]
              }
            }
          ]
        }


      ],


      searchKey: '',
      currentPrint: null,
      currentRow: null,
      table1Height: 300,
      addText: '',
      InkjetPrinterData: [

      ],
      fonts: [
        { value: 'Arial', label: 'Arial' }
      ],
      fontSpacings: [
        { value: 5, label: '5' },
        { value: 4, label: '4' },
        { value: 3, label: '3' },
        { value: 2, label: '2' },
        { value: 1, label: '1' },
        { value: 0, label: '0' },
        { value: -1, label: '-1' },
        { value: -2, label: '-2' },
        { value: -3, label: '-3' },
        { value: -4, label: '-4' },
        { value: -5, label: '-5' },
      ],

      detailsData: [

      ],

      //开工的记录
      startData: [


      ]



    };


    return pageData;
  },


  created() {
    this.printerInit(() => {


    });

    this.sqDepartmentsInit();
    this.sequanceDataInit();
    this.heightInit();
  },
  // 函数
  methods: {

    onDateChange(date) {

      if (date && date.length) {
        this.start_time = toDateString(date[0]._d, 'yyyy/MM/dd') + ' 00:00';
        this.end_time = toDateString(date[1]._d, 'yyyy/MM/dd') + ' 23:59:59';
      } else {
        this.start_time = null;
        this.end_time = null;
      }

    },


    pageSetting(row) {
      this.$openPage("/InkjetPrinter/InkjetPrinterSetting/" + row.id); // 打开页面  
    },
    getSearchParms() {
      var rules = [];
      let findMode = k => {
        for (let i in this.searchRules) {
          if (this.searchRules[i].key == k) return this.searchRules[i].mode;
        }
        return "equal";
      };

      for (let key in this.searchFormData) {
        let value = this.searchFormData[key];
        if (value) {
          let mode = findMode(key);
          rules.push({
            field: key,
            op: mode,
            value: value
          });
        }

      }
      if (this.start_time) {
        rules.push({
          field: 'voucherdate',
          op: 'greaterorequal',
          value: this.start_time
        });
      }
      if (this.end_time) {
        rules.push({
          field: 'voucherdate',
          op: 'lessorequal',
          value: this.end_time
        });
      }
      return {
        op: 'and', groups: [], rules: rules
      };
    },
    sequanceDataInit() {
      this.$mk.post({
        url: this.actions.sequanceData,
        loading: "加载中...",
        data: {
          filter: this.getSearchParms()
        }
      }).then(a => {
        if (a.code == 200) {
          let ds = [];
          a.data.sqList.forEach(item => {
            let o = item;
            if (o.voucherdate) {
              o.voucherdate = o.voucherdate.substr(0, 10)
            }
            ds.push(o)
          });
          this.startData = a.data.startList;
          ds = JSON.parse(JSON.stringify(ds))

          let ds_full = [];
          ds.forEach(item => {

            this.InkjetPrinterData.forEach(pitem => {
              let item1 = JSON.parse(JSON.stringify(item));
              item1.sequance = item.sequance.substr(0, item.sequance.length - 1) + pitem.code + item.sequance.substr(item.sequance.length - 1);
              item1.printerCode = pitem.code;
              item1.printerId = pitem.id.toString();
              item1.printerName = pitem.name;
              ds_full.push(item1);
            });


          });
          this.detailsData = ds;

          this.$forceUpdate();
        }
      });
    },

    // 通用行合并函数（将相同多列数据合并为一行）
    rowspanMethod({ row, _rowIndex, column, visibleData }) {



      let fields = ['voucherdate', 'vouchercode', 'departmentName', 'inventoryName', 'quantity']

      let rowField = 'bid';

      let cellValue = row[rowField]
      if (cellValue && fields.includes(column.property)) {
        let prevRow = visibleData[_rowIndex - 1]
        let nextRow = visibleData[_rowIndex + 1]



        if (prevRow && prevRow[rowField] === cellValue) {
          return { rowspan: 0, colspan: 0 }
        } else {
          let countRowspan = 1
          while (nextRow && nextRow[rowField] === cellValue) {
            nextRow = visibleData[++countRowspan + _rowIndex]
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 }
          }
        }
      }
    },
    sqDepartmentsInit() {
      this.$mk.post({
        url: this.actions.getSqDepartments,
        loading: "加载中...",
        data: {
        }
      }).then(a => {
        if (a.code == 200) {
          let ds = [];
          a.data.forEach(item => {
            ds.push({ value: item.name, label: item.name });
          });

          this.searchFormItems[1].children[0].itemRender.props.options = ds;
        }
      });
    },

    onSearch() {


      this.printerInit(() => {

        this.sequanceDataInit();

      })



    },
    isDisabled1(row) {

      if(!this.currentPrint){
        return true;
      }
      let v = false;

      this.startData.forEach(item=>{
        if(item.bid == row.bid && item.printerId == this.currentPrint.id.toString()){ 
          v = true;
        } 
      })

      return v; 
    },
    isDisabled2(row) {
      if(!this.currentPrint){
        return true;
      }

     let v = true;

      this.startData.forEach(item=>{
        if(item.bid == row.bid && item.printerId == this.currentPrint.id.toString()){ 
          v = false;
        } 
      })

      return v; 
    },

    printerInit(callback) {
      if (this.InkjetPrinterData.length) {
        callback();
      } else {
        this.$mk.post({
          url: this.actions.get,
          loading: "加载中...",
          data: {
            "end_time": 0,
            "page": 1,
            "start_time": 0,
            "limit": 999,
            "order_bys": [
            ],
            "search_rules": [
            ]
          },
          useBigInt: true
        }).then(a => {

          this.InkjetPrinterData = a.data.InkjetPrinter;
          callback();
        });

      }

    },



    getDefaultData(item) {
      return Object.assign(item, { x: 0, y: 0, direction: 0, fontName: 'Arial', fontSize: 100, fontSpacing: 10 });
    },

    pageAdd() {


      this.detailsData = [...this.detailsData, this.getDefaultData({ sequance: this.searchKey })];

    },



    heightInit() {

      this.$nextTick(() => {
        let h = this.$mk.getWindowSize().height - this.$mk.getOffsetTop(this.$refs.xTable.$el) - 360;
        if (h < 250) {
          h = 250;
        }

        this.table1Height = h;
      });

    },
    loadData() {
    },

    toggleCard(item) {

      this.InkjetPrinterData.forEach(o => {
        o.isSelected = false;
      })

      item.isSelected = true;
      this.currentPrint = item;
      this.$forceUpdate();
    },
    pageShowDone(item) {
      if(!this.currentPrint){
        return;
      }
      this.currentRow = item

      let pitem = this.currentPrint;
      let item1 = JSON.parse(JSON.stringify(item)); 
      item1.printerCode = pitem.code;
      item1.printerId = pitem.id.toString();
      item1.printerName = pitem.name;

      this.startData.forEach(item=>{ 
        if(item.bid == item.bid && item.printerId == this.currentPrint.id.toString()){
          item1.groupType = item.groupType;
          item1.sequance = item.sequance;
        }
      })



      this.$mk.dialog.open({
        page: () => import("./modal-done.vue"),
        title: "完工",
        pageOptions: item1,
        width: 500,
        height: 200,
        callback:()=>{
          this.sequanceDataInit();
        }
      });
    },
    print(row) { // 打印 
      let hiprint = this.$hiPrint; // 获取打印组件
      let tdata = JSON.parse(JSON.stringify(row)); // 复制表单数据

      this.startData.forEach(item=>{ 
        if(item.bid == row.bid && item.printerId == this.currentPrint.id.toString()){
           tdata.groupType = item.groupType;
            tdata.sequance = item.sequance;
        }
      })


      let oldValue = localStorage.getItem('print-template-1');
      let template = JSON.parse(JSON.stringify(printSetting.printTagTemplate));
      if (oldValue) {
        template = JSON.parse(oldValue).TemplateBody;
      }
      hiprint.init(); // 初始化打印组件 
      var hiprintTemplate = new hiprint.PrintTemplate({ // 创建打印模板
        template: template
      });
      hiprintTemplate.print(tdata, { printer: '', title: '标签打印' }); // 打印
    },

    pageShowSend(item) {

      if (!this.currentPrint) {
        this.$mk.error('请先选择机器');
        return;
      }
      this.currentRow = item

      let pitem = this.currentPrint;
      let item1 = JSON.parse(JSON.stringify(item));
      item1.sequance = item.sequance.substr(0, item.sequance.length - 1) + pitem.code + item.sequance.substr(item.sequance.length - 1);
      item1.printerCode = pitem.code;
      item1.printerId = pitem.id.toString();
      item1.printerName = pitem.name;

      this.$mk.dialog.open({
        page: () => import("./modal-send.vue"),
        title: "开工",
        pageOptions: item1,
        width: 500,
        height: 500,
        callback:()=>{
          this.sequanceDataInit();
        }
      });
    },
    pageStart(item) {
      var sendData = {
        id: this.$mk.toBigInt(item.id)
      };
      this.$mk.post({
        url: `${BASE_URL.BASE_URL}/InkjetPrinter/v1/start/machine`,
        loading: "启动中...",
        data: sendData,
        useBigInt: true
      }).then(a => {
        if (a.code != 200) {
          this.$mk.error(a.msg);
        } else {
          this.$mk.success(a.msg || "启动成功");
        }
      });
    },

    pageStop(item) {
      var sendData = {
        id: this.$mk.toBigInt(item.id)
      };
      this.$mk.post({
        url: `${BASE_URL.BASE_URL}/InkjetPrinter/v1/stop/machine`,
        loading: "停止中...",
        data: sendData,
        useBigInt: true
      }).then(a => {
        if (a.code == 200) {
          this.$mk.success(a.msg || "停止成功");
        }
      });
    },
    pageGetPrintInfo(row) {
      if (!this.currentPrint) {
        this.$mk.error("请先选择机器");
        return;
      }
      var sendData = {};
      sendData.id = this.$mk.toBigInt(this.currentPrint.id);
      this.$mk.post({
        url: `${BASE_URL.BASE_URL}/InkjetPrinter/v1/get/print/statistics`,
        loading: "获取中...",
        data: sendData,
        useBigInt: true
      }).then(a => {
        if (a.code != 200) {
          this.$mk.error(a.msg);
        } else {
          if (a.data && a.data.print_statistics) {
            row.print_statistics = a.data.print_statistics;

            this.$forceUpdate();
          }
        }
      });
    },

    pageSend(item) {
      if (!this.currentPrint) {
        this.$mk.error("请先选择机器");
        return;
      }
      var sendData = Object.assign({}, item);
      delete sendData._X_ROW_KEY;
      delete sendData.print_statistics;
      sendData.id = this.$mk.toBigInt(this.currentPrint.id);
      sendData.contents = sendData.sequance;
      sendData.fileName = "";
      delete sendData.sequance
      delete sendData.voucherdate
      delete sendData.vouchercode
      delete sendData.inventoryName
      delete sendData.quantity
      delete sendData.departmentName
      this.$mk.post({
        url: `${BASE_URL.BASE_URL}/InkjetPrinter/v1/send/print/file`,
        loading: "发送文件中...",
        data: sendData,
        useBigInt: true
      }).then(a => {
        if (a.code == 200) {
          this.$mk.error(a.msg);
        } else {
          this.$mk.success(a.msg || "发送成功");
        }
      });
    },

    cancel() {
      this.$emit("callback", {});
    }
  },
  // 监听属性
  watch: {

  }
};

</script>
<style>
.page-body {
  background: white;
}

.printcard-container {
  display: flex;
  flex-wrap: wrap;
}

.printcard {
  width: calc(33.33% - 20px);
  /* 调整卡片宽度，包括间距 */
  margin: 10px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  /* 添加阴影效果 */
  transition: box-shadow 0.3s ease;
  /* 添加过渡效果 */

  cursor: pointer;
}

.printcard:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  /* 鼠标悬停时增加阴影效果 */
}

.printcard-content {
  font-size: 16px;
  color: #333;
  line-height: 1.5;
  position: relative;
  padding-bottom: 20px;
}

.printcard-content .ant-input {
  margin-bottom: 5px;
}

.printcard-header {
  display: flex;
}

.printcard-title {
  flex: 2;
}

.printcard-buttons {
  flex: 1;
}

.printcard-selected {
  background-color: #b2d9f1;
}

.printcard-toolbar {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>
