<template>
  <div style="width: 98% !important">
    <Navbar title="设备打印" :is-go-back="false" />
    <div class="all">
      <div class="globalMain">
        <ul class="siteList">
          <li class="last">
            <div class="site">
              <label class="labelStyle">所属部门</label>
              <div class="form-inline-div">
                <SearchWidget style="width: 200px" :info-window-no="organizationWindowNo" :field="organizationField"
                  :field-value="organizationFieldValue" :display-name="organizationField.listDisplayFieldName"
                  :where-clause-source="organizationWCS" @value-changed="organizationValueChanged" />
              </div>
            </div>
          </li>
          <li class="site">
            <label class="labelStyle">名称</label>
            <div class="form-inline-div">
              <a-input v-model:value="searchParams.name" class="form-input" @keyup.enter="reQuery" />
            </div>
          </li>
          <li class="site">
            <label class="labelStyle">编号</label>
            <div class="form-inline-div">
              <a-input v-model:value="searchParams.no" class="form-input" @keyup.enter="reQuery" />
            </div>
          </li>
          <li class="site">
            <label class="labelStyle">规格型号</label>
            <div class="form-inline-div">
              <a-input v-model:value="searchParams.type" class="form-input" @keyup.enter="reQuery" />
            </div>
          </li>
          <li class="site">
            <label class="labelStyle">{{ $t("lang.AssetLabelPrint.printStatus") }}</label>
            <div class="form-inline-div">
              <a-select v-model:value="searchParams.printStatus" class="form-input"  @change="reQuery">
                <a-select-option :value="null">{{ $t("lang.AssetLabelPrint.all") }}</a-select-option>
                <a-select-option :value="false">
                  {{ $t("lang.AssetLabelPrint.notPrint") }}
                </a-select-option>
                <a-select-option :value="true">
                  {{ $t("lang.AssetLabelPrint.havePrint") }}
                </a-select-option>
              </a-select>
            </div>
          </li>
        </ul>
      </div>
      <ul class="siteList">
        <li class="site">
          <label class="labelStyle">{{ $t("lang.AssetLabelPrint.selectPrintTemplate") }}</label>
          <div class="form-inline-div">
            <a-select v-model:value="templateId" class="form-input">
              <a-select-option value="" />
              <a-select-option v-for="item in templates" :key="'templates' + item.name" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </div>
        </li>
        <li class="site">
          <label for="selectPrinter" class="labelStyle">{{ $t("lang.AssetLabelPrint.selectPrinter") }}</label>
          <div class="form-inline-div">
            <a-select v-model:value="selectedPrinter" class="form-input">
              <a-select-option value="" />
              <a-select-option v-for="printer in printers" :key="printer" :value="printer">
                {{ printer }}
              </a-select-option>
            </a-select>
          </div>
        </li>
        <li style=" margin-left: 36px; display: flex; justify-content: space-between; ">
          <a-button type="primary" style="width: 80px" @click="print()">
            {{ $t("lang.AssetLabelPrint.print") }}
          </a-button>
          <PrintEpc ref="printEpc" v-model:visible="printEpcVisible" :printer-name="selectedPrinterCard"
            @ok="closePrintEpc" />
          <a-button type="primary" style="width: 80px;margin-left: 12px" @click="reQuery()">
            {{ $t("lang.AssetLabelPrint.query") }}
          </a-button>
          <a-button style="width: 80px; margin-left: 12px" type="dashed" @click="clearFilter()">
            {{ $t("lang.AssetLabelPrint.clear") }}
          </a-button>
        </li>
      </ul>
    </div>

    <CommonTable ref="commonTableRef" :extra-height="70" :columns="labelPrintColumns"
      :data-source="assetInstanceDtoList" :total="pagination.total" :is-select="true" @get-pager="getPageParams"
      @get-selected="getSelectParams">
      <template #bodyCell="{ column, record }">
        <div v-if="column.dataIndex === 'printStatus'">
          {{ record.printStatus ? '已打印' : '未打印' }}
        </div>
        <div v-if="column.dataIndex === 'operate'">
          <a-button style="width: 80px; margin-left: 12px" type="dashed" @click="cardEpc(record.epc)">
            发卡
          </a-button>
        </div>
      </template>
    </CommonTable>

    <WriteEpc ref="writeEpc" v-model:visible="writeEpcVisible" @ok="closePrintEpc" />

    <Loading v-if="loading" />
  </div>
</template>

<script>
import Printer from './printer.js';
import { message } from 'ant-design-vue';
import CommonTable from '../common/CommonTable.vue';
import { assetLabelPrintColumns } from './columns.js';
import { Common, Notify, PrintEpc,WriteEpc } from 'pc-component-v3';

export default {
  components: { PrintEpc, CommonTable,WriteEpc },
  data: function () {
    return {
      assetInstanceDtoList: [],
      checked: false, //全选,
      labelPrintColumns: assetLabelPrintColumns,
      pagination: {
        total: 0, //总页数
        per_page: 20, // 每页大小
        current_page: 1, // 当前页数
        last_page: 0, // 最后一页编号
      },
      rangeDate: [],
      // 请求查询参数
      searchParams: {
        no: null, // 资产编号
        name: null, // 资产名称
        type: null,
        printStatus: null, // 打印状态
        organizationId: null, // 部门id
      },
      userWindowNo: '050408',
      organizationWindowNo: '20220420_233656',
      organizationField: {
        name: '',
        listDisplayFieldName: 'name',
      },
      organizationFieldValue: {
        id: null,
        displayValue: [''],
        fieldType: 'Key',
      },
      custodianNameField: {
        name: '',
        listDisplayFieldName: 'name',
      },
      custodianNameFieldValue: {
        id: null,
        displayValue: [''],
        fieldType: 'Key',
      },
      userField: {
        name: '',
        listDisplayFieldName: 'name',
      },
      userFieldValue: {
        id: null,
        displayValue: [''],
        fieldType: 'Key',
      },
      applyPurchaseUserField: {
        name: '',
        listDisplayFieldName: 'name',
      },
      applyPurchaseUserFieldValue: {
        id: null,
        displayValue: [''],
        fieldType: 'Key',
      },
      organizationWCS: {
        customerDataDimensions: [
          {
            fieldName: 'client.id',
            dataDimensionTypeNo: '202201191757',
            defaultDataDimensionTypeValueNo: '4',
          },
        ],
      },
      custodianIdWhereClauseSource: {
        customerDataDimensions: [
          {
            fieldName: 'client.id',
            dataDimensionTypeNo: '202201191757',
            defaultDataDimensionTypeValueNo: '4',
          },
        ],
      },
      templates: [], //打印模板
      printers: [], //打印机
      selectedPrinter: '', // 选择的打印机
      templateId: '',
      printPages: [],
      printPreviews: [],
      loading: false,
      modal: false,
      selectedPrinterCard: '发卡机',
      printEpcVisible: false,
      isCardEpc: false,
      selectedIds: [],
      writeEpcVisible: false,
    };
  },
  computed: {},

  watch: {},
  mounted: function () {
    const _self = this;

    _self.pagination.current_page = 1;
    _self.getAssetInstancePrint();
    _self.loadTemplateData();

    Printer.getPrinters().then(
      success => {
        if (success.errorCode === 0) {
          if (success.data && success.data.length > 0) {
            success.data.forEach(item => {
              _self.printers.push(item);
            });
          }
        } else {
          message.warning(success.errorMessage);
        }
      },
      error => {
        console.log(error);
      },
    );
  },

  beforeUnmount: function () { },

  methods: {
    // 所属部门搜索框条件改变
    organizationValueChanged: function (newFieldValue) {
      this.organizationFieldValue = newFieldValue;
      this.searchParams.organizationId = newFieldValue.id;
    },
    // 责任人
    custodianNameValueChanged: function (newFieldValue) {
      this.custodianNameFieldValue = newFieldValue;
      this.searchParams.custodianId = newFieldValue.id;
    },
    // 保管人
    userValueChanged: function (newFieldValue) {
      this.userFieldValue = newFieldValue;
      this.searchParams.depositoryUserId = newFieldValue.id;
    },
    // 申购人
    applyPurchaseUserValueChanged: function (newFieldValue) {
      this.applyPurchaseUserFieldValue = newFieldValue;
      this.searchParams.applyPurchaseUserId = newFieldValue.id;
    },
    /**
     * 获取选择数据的id集合
     */
    getSelectedRecordIds: function () {
      const _self = this;
      // let recordIds = [];

      // for (let i = 0; i < _self.assetInstanceDtoList.length; i++) {
      //   if (_self.assetInstanceDtoList[i].checked == true) {
      //     recordIds.push(_self.assetInstanceDtoList[i].assetInstanceId);
      //   }
      // }

      return _self.selectedIds;
    },

    onRangeChange(_, str) {
      this.searchParams.startDate = str[0] === '' ? null : str[0];
      this.searchParams.endDate = str[1] === '' ? null : str[1];
    },

    getPageParams(page, pageSize) {
      this.pagination.current_page = page;
      this.pagination.per_page = pageSize;
      this.getAssetInstancePrint();
    },
    getSelectParams(selected) {
      const _self = this;
      if (_self.isCardEpc) {
        return;
      }
      let templateId = _self.templateId;
      if (templateId == '' || templateId == null) {
        _self.templateId = '';
        _self.$refs.commonTableRef.clear(false);
        Notify.error('错误', '请先选择打印模板', false);
        return;
      }

      _self.selectedIds = selected.selectedRowKeys;
    },

    getPrintData: function (recordIds) {
      const _self = this;
      let contents = [];

      $.ajax({
        url: Common.getApiURL(
          'AssetInstanceResource/print?printPreview=' +
          false +
          '&templateId=' +
          _self.templateId,
        ),
        dataType: 'json',
        type: 'post',
        contentType: 'application/json',
        data: JSON.stringify(recordIds),
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
          _self.loading = true;
        },
        success: function (datas) {
          datas.forEach(function (item) {
            var printItem = {
              id: null,
              name: null,
              content: item,
            };
            if (
              printItem.content == null ||
              printItem.content.printItems == null ||
              printItem.content.printItems.length == 0
            ) {
              Notify.error('错误', '打印模板无数据，不能打印。');
              return;
            }
            var content = JSON.stringify(printItem.content);
            if (content == null || content == '' || content == '{}') {
              Notify.error('错误', '请先选择模板，再点击下载。');
              return;
            }
            contents.push(printItem.content);
          });
          _self.loading = false;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 打印文件
     */
    print: function () {
      const _self = this;
      let templateId = _self.templateId;
      if (templateId == null || templateId.length == 0) {
        Notify.error('提示', '请先选择打印模板。', false);
        return;
      }

      let selectedPrinter = _self.selectedPrinter;
      if (selectedPrinter == null || selectedPrinter.length == 0) {
        Notify.error('提示', '请先选择打印机。', false);
        return;
      }

      let recordIds = _self.getSelectedRecordIds();
      if (recordIds == null || recordIds.length == 0) {
        Notify.error('提示', '请先选择打印数据。', false);
        return;
      }
      console.log(templateId, recordIds, selectedPrinter, '打印数据');
      const cardIds = recordIds.join();
      const url = `/barcode.html#/chartPrint?templateId=${templateId}&printName=${selectedPrinter}&cardIds=${cardIds}&type=Inventory`;
      window.open(url);
    },

    cardEpc: function (epc) {
      const _self = this;
      _self.writeEpcVisible = true;
      _self.$refs.writeEpc.writeSingleEpc(epc);
    },

     writeSelectEpc: function () {
      const datas = [];
      const tableDatas = JSON.parse(
        JSON.stringify(this.assetInstanceDtoList),
      );
      if (tableDatas && tableDatas.length > 0) {
        const isSelect = tableDatas.some(item => {
          return item.checked == true;
        });
        console.log(isSelect);
        if (!isSelect) {
          Notify.error('提示', '请选择一条发卡数据。', false);
          return;
        }
        tableDatas.forEach(item => {
          if (item.checked) {
            datas.push(item.epc);
          }
        });
        if (datas.length > 1) {
          Notify.error('提示', '请至多选择一条发卡数据。', false);
          return;
        }
        this.writeEpcVisible = true;
        this.$refs.writeEpc.writeSingleEpc(datas[0]);
      }
    },

    closePrintEpc: function () {
      const _self = this;
      _self.writeEpcVisible = false;
    },

    /**
     * 打印模板change
     */
    templateChange: function (assetInstance) {
      const _self = this;
      if (_self.isCardEpc) {
        return;
      }
      let templateId = _self.templateId;
      if (templateId == '' || templateId == null) {
        _self.templateId = '';
        assetInstance.checked = false;
        Notify.error('错误', '未请先选择打印模板', false);
        return;
      }
    },

    /**
     * 设置模板
     */
    setTemplate: function (assetInstanceId, templateId) {
      var _self = this;
      _self.loading = true;
      $.ajax({
        url: Common.getApiURL('AssetInstanceResource/setPrintTemplate'),
        type: 'get',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        data: {
          assetInstanceId: assetInstanceId,
          templateId: templateId,
        },
        success: function (data) {
          _self.loading = false;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 加载打印模板数据
     */
    loadTemplateData: function () {
      var _self = this;

      Printer.queryTemplates().then(
        success => {
          if (success.errorCode === 0) {
            if (success.datas && success.datas.length > 0) {
              _self.templates = success.datas;
            }
          } else {
            message.warning(success.errorMessage);
          }
        },
        error => {
          Common.processException(error);
        },
      );
    },

    /**
     * 20200615
     * 点击全选
     */
    selectAll: function () {
      var _self = this;
      for (var i = 0; i < _self.assetInstanceDtoList.length; i++) {
        _self.assetInstanceDtoList[i].checked = _self.checked;
      }
    },

    /**
     * 重新查询
     */
    reQuery: function () {
      let _self = this;
      _self.$refs.commonTableRef.backFirstPage();
    },

    /**
     * 查询资产卡片打印的数据
     */
    getAssetInstancePrint: function () {
      var _self = this;
      _self.loading = true;

      _self.checked = false;
      const range = {
        start: (_self.pagination.current_page - 1) * _self.pagination.per_page,
        length: _self.pagination.per_page,
      };
      const searchParams = _self.searchParams;
      const params = { ...searchParams, ...{ range }, inventoryType: 'Instrument' };
      $.ajax({
        url: Common.getApiURL('InventoryResource/queryInventoryPrint'),
        type: 'post',
        contentType: 'application/json',

        dataType: 'json',
        data: JSON.stringify(params),
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (successData) {

          if (successData.errorCode == 0) {
            if (successData.datas && successData.datas.length > 0) {
              _self.assetInstanceDtoList = successData.datas;
              _self.assetInstanceDtoList.forEach(function (item) {
                item.id = item.inventoryId;
                item.checked = false;
              });

            } else {
              _self.assetInstanceDtoList = [];
            }
            _self.pagination.total = successData.total;
          }
          _self.loading = false;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
          _self.loading = false;
        },
      });
    },

    /**
     * 清空条件
     */
    clearFilter: function () {
      const _self = this;
      (_self.searchParams = {
        epc: null,
        assetNo: null,
        assetInstanceName: null,
        printStatus: null,
        type: null,
        organizationId: null,
        custodianId: null,
        depositoryUserId: null,
        applyPurchaseUserId: null,
        locationName: null,
        startDate: null,
        endDate: null,
      }),
        _self.rangeDate = [];
      (_self.organizationFieldValue = {});
      _self.custodianNameFieldValue = {};
      _self.userFieldValue = {};
      _self.applyPurchaseUserFieldValue = {};
      _self.reQuery();
    },

    /**
     * 修改页Size
     */
    gridSizeSelect: function (newPageSize) {
      this.pagination.per_page = newPageSize;
      this.pagination.current_page = 1;
      this.getAssetInstancePrint();
    },
  },
};
</script>



<style scoped>
.grid-container {
  display: grid;
  grid-template-columns: 100%;
  /*将视图分为四个模块，每个模块的高度*/
  grid-template-rows: 53px min-content auto 40px;
  /*视口被均分为 100 单位的 vh 占据整个窗口，扣掉顶部 topNav 的距离后，计算得到 responseOrgnizationSelect 的高度*/
  height: calc(100vh - 90px);
  width: 100%;
  overflow: hidden;
}

.grid-item-1 {
  grid-column: 1 / 2;
  grid-row: 1 / 2;
}

.grid-item-2 {
  grid-column: 1 / 2;
  grid-row: 2 / 3;
}

.grid-item-3 {
  padding-top: 0px;
  padding-right: 10px;
  overflow: hidden;
  grid-column: 1 / 2;
  grid-row: 3/4;
  height: 100%;
}

.grid-item-4 {
  padding-top: 10px;
  grid-column: 1 / 2;
  grid-row: 4/5;
}
</style>

<style scoped>
.m-form-group {
  margin-left: 5px !important;
  margin-right: 5px !important;
  margin-bottom: 5px !important;
}

@media (max-width: 768px) {
  .m-form-group-label {
    text-align: left;
    padding-right: 10px;
  }
}

@media (min-width: 768px) {
  .m-form-group-label {
    width: 100px;
    text-align: center;
    padding-right: 10px;
  }

  .input-switches {
    width: 100%;
  }
}

.form-control-complex {
  width: 200px !important;
}

.form-input {
  border-radius: 4px !important;
}

.m-form-input {
  border-radius: 4px !important;
  width: 200px !important;
}

.form-inline-div {
  display: inline-block;
  height: 34px;
}

.m-btn {
  margin-left: 5px !important;
  margin-right: 5px !important;
  margin-bottom: 5px !important;
}

.table-header-left {
  float: left;
  /* margin: 20px 0; */
}

.table-header-right {
  margin-top: -2px;
  float: right;
}
</style>

<style scoped>
.room_img {
  width: 150px;
  height: 100px;
  float: left;
  margin-right: 10px;
}

.room_img img {
  width: 100%;
  height: 100%;
}

.room_img span {
  position: relative;
  right: -130px;
  top: -100px;
  font-size: 20px;
  color: red;
}

.modal-img-box {
  width: 100%;
  height: 400px;
  text-align: center;
  overflow: auto;
}

.m-small-img {
  cursor: pointer;
}

.m-img {
  width: 100%;
}

.labelStyle {
  width: 120px;
  text-align: right;
  padding: 8px;
}

.grid-item-row2-column2 {
  grid-row-start: 2;
  grid-row-end: 3;
  grid-column-start: 2;
  grid-column-end: 3;
  overflow: auto;
  margin-top: 0px;
}

.globalMain {
  max-width: 100%;
  margin-left: auto;
  margin-right: auto;
}

.siteList {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

@media (min-width: 500px) {
  .siteList {
    margin-left: 0;
    margin-right: -25px;
    justify-content: flex-start;
  }
}

.siteList>li {
  margin-bottom: 10px;
}

@media (min-width: 500px) {
  .siteList>li {
    margin-right: 8px;
  }
}

.siteList .site {
  width: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  /* flex-direction: column; */
  position: relative;
}

* {
  margin: 0;
  padding: 0;
  list-style: none;
  box-sizing: border-box;
}

.form-input {
  width: 200px !important;
  height: 30px !important;
  padding-left: 6px !important;
}
</style>