<template>
  <div>
    <div v-show="printing">
      <Navbar title="标签打印" :is-go-back="true" />
      <div class="printDiv">
        <div>
          <span style="color: red"> * </span>
          <label>导入批次：</label>
          <a-select
            v-model:value="queryParams.batchNo"
            show-search
            class="commonStyle"
            :options="batchNos.map((item) => ({ value: item.label }))"
            @change="batchNoChange"
          />
          <label>保管人员：</label>
          <a-select
            v-model:value="queryParams.depositoryUser"
            show-search
            class="commonStyle"
            :options="depositoryUsers.map((item) => ({ value: item.label }))"
            @change="searchDatas"
          />
          <label>打印状态：</label>
          <a-select
            v-model:value="queryParams.labelPrintType"
            show-search
            class="commonStyle"
            :options="
              statusOptions.map((item) => ({
                value: item.value,
                label: item.label,
              }))
            "
            @change="searchDatas"
          />
        </div>
        <div style="margin: 8px 0 0 9px">
          <label>公司名称：</label>
          <a-select
            v-model:value="queryParams.clientName"
            show-search
            class="commonStyle"
            :options="clientNames.map((item) => ({ value: item.label }))"
            @change="searchDatas"
          />
          <label>所属部门：</label>
          <a-select
            v-model:value="queryParams.organizationName"
            show-search
            class="commonStyle"
            :options="organizationNames.map((item) => ({ value: item.label }))"
            @change="searchDatas"
          />
          <label>成本中心：</label>
          <a-select
            v-model:value="queryParams.costCenterName"
            show-search
            class="commonStyle"
            :options="costCenterNames.map((item) => ({ value: item.label }))"
            @change="searchDatas"
          />
          <a-button type="primary" @click="searchDatas">查询</a-button>
        </div>
        <div style="margin-top: 8px">
          <span style="color: red"> * </span>
          <label>打印模板：</label>
          <a-select
            v-model:value="printTemplate"
            show-search
            class="commonStyle"
            :options="
              templateNames.map((item) => ({
                value: `${item.id}-${item.name}`,
                label: item.name,
              }))
            "
            @change="getTemplateInfo"
          />
          <a-button
            type="dashed"
            style="margin-right: 16px"
            @click="printPreview"
          >
            效果预览
          </a-button>
          <a-button
            type="dashed"
            style="margin-right: 16px"
            @click="showPrintInfo"
          >
            打印
          </a-button>
          <a-button type="dashed" style="margin-right: 16px" @click="printAll">
            打印全部
          </a-button>
          <a-button type="dashed" @click="downloadImageZip">
            下载全部
          </a-button>
        </div>
        <a-divider />
        <CommonTable
          ref="table"
          :total="total"
          :columns="columns"
          :is-loading="isLoading"
          :is-select="isSelect"
          :data-source="dataSource"
          @select-column="selectColumn"
          @page-params="getPageParams"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'imageUrl'">
              <a-image
                :width="100"
                :height="50"
                :src="getImageSrc(className, record.imageUrl)"
              />
            </template>
          </template>
        </CommonTable>
        <a-modal
          v-model:visible="printVisible"
          title="包装信息"
          ok-text="确认"
          cancel-text="取消"
          @ok="
            all === false
              ? printCard(select.selectedRows)
              : printCard(select.allData)
          "
        >
          <label>包装批号：</label>
          <a-input
            id="displayName"
            v-model:value="packageBatchNo"
            :disabled="true"
          />
          <label>上次的批号：</label>
          <a-input v-model:value="lastPackageBatchNo" :disabled="true" />
          <label>包装名称：</label>
          <a-input
            id="displayName"
            v-model:value="packageName"
            :disabled="true"
          />
          <label>上次的名称：</label>
          <a-input v-model:value="lastPackageName" :disabled="true" />
          <div class="operationBtn">
            <a-button type="dashed" style="width: 240px" @click="lastTime">
              同上一次
            </a-button>
            <a-button
              type="dashed"
              style="width: 240px; margin-left: 4px"
              @click="createNew"
            >
              生成新的
            </a-button>
          </div>
        </a-modal>
        <a-modal
          v-model:visible="imageVisible"
          title="效果预览"
          :mask-closable="false"
          :body-style="bodyStyle"
        >
          <a-image :src="imageUrls[0]" />
          <template #footer />
        </a-modal>
        <Loading v-if="globalLoading" :text="propText" />
      </div>
    </div>
    <div ref="hua" style="float: left; z-index: -999" />
  </div>
</template>

<script setup>
import Common from '../common/Common';
import CreateJPEG from '../common/X6';
import { message } from 'ant-design-vue';
import { base64toFile } from '../common/X6';
import CommonTable from './CommonTable.vue';
import { SqlApi, Notify } from 'pc-component-v3';
import { getImageSrc } from '../common/image-src';
import { ref, reactive, onMounted, watch } from 'vue';
import {
  columns,
  dateConvert,
  multipleImageUpload,
  getTemplate,
  downloadZip,
} from './config';

const className = ref('com.leanwo.prodog.print.model.LabelPrintLine');
const table = ref(null);
const imageUrls = reactive([]);
const printing = ref(true);
const total = ref(0);
const isSelect = ref(true);
const isLoading = ref(false);
const select = reactive({ selectedRows: [], allData: [] });
const dataSource = ref([]);
const printVisible = ref(false);
const imageVisible = ref(false);
const visible = ref(false);
const globalLoading = ref(false);
const all = ref(false);
const propText = ref('');
const bodyStyle = {
  display: 'flex',
  justifyContent: 'center',
};
const batchNos = ref([]);
const clientNames = ref([]);
const depositoryUsers = ref([]);
const costCenterNames = ref([]);
const organizationNames = ref([]);
const statusOptions = ref([
  {
    value: '',
    label: '',
  },
  {
    value: 'To_Be_Printed',
    label: '待打印',
  },
  {
    value: 'Printing',
    label: '打印中',
  },
  {
    value: 'Printed',
    label: '已打印',
  },
]);
const queryParams = reactive({
  batchNo: '',
  depositoryUser: '',
  labelPrintType: '',
  clientName: '',
  organizationName: '',
  costCenterName: '',
});
const pager = reactive({
  start: 0,
  length: 20,
});
const templateId = ref('');
const allTemplate = ref([]);
const templateData = ref(null);
const lastBatchNo = ref('');
const printTemplate = ref('');
const templateNames = ref([]);
const packageBatchNo = ref('');
const lastPackageBatchNo = ref('');
const packageName = ref('');
const lastPackageName = ref('');
const newPackageName = ref('');
const hua = ref(null);
const clientId = ref('');
let getBase64;
// 获取分页
const getPageParams = (start, length) => {
  pager.start = (start - 1) * length;
  pager.length = length;
  searchPrintInfo();
};
// 批次号切换
const batchNoChange = () => {
  queryParams.clientName = '';
  queryParams.depositoryUser = '';
  queryParams.costCenterName = '';
  queryParams.organizationName = '';
  queryParams.labelPrintType = '';
  commonSqlApi('20230613_192444', depositoryUsers); // 查询保管人
  commonSqlApi('20230613_193808', clientNames); // 查询公司
  commonSqlApi('20230613_194108', organizationNames); // 查询部门
  commonSqlApi('20230613_194557', costCenterNames); // 查询成本中心
  table.value.clear(); // 清空选择
  table.value.backFirstPage(); // 回到第一页
};
// 查询回到第一页
const searchDatas = () => {
  table.value.backFirstPage();
};
// 查询信息
const searchPrintInfo = () => {
  isLoading.value = true;
  clientId.value = JSON.parse(localStorage.getItem('#LoginInfo')).loginClientId;
  let params = { ...queryParams, ...pager, clientId: clientId.value };
  if (queryParams.batchNo !== '') {
    SqlApi.execute('20230613_140456', params).then(
      successData => {
        const { lines, errorMessage, errorCode } = successData;
        if (errorCode == 0) {
          total.value = successData.total;
          dataSource.value = lines;
          select.allData = lines;
          isLoading.value = false;
        } else {
          Notify.error('查询异常', errorMessage, true);
        }
        isLoading.value = false;
      },
      errorData => {
        Common.processException(errorData);
        isLoading.value = false;
      },
    );
  } else {
    isLoading.value = false;
  }
};
// 获取所选项的数据
const selectColumn = rows => {
  select.selectedRows = rows;
  // console.log('onSelectChange', select.selectedRows);
};
// 展开打印框
const showPrintInfo = () => {
  if (printTemplate.value !== '' && queryParams.batchNo !== '') {
    printVisible.value = true;
    const nameArr = [];
    const obj = JSON.parse(JSON.stringify(queryParams));
    delete obj.labelPrintType;
    for (let key in obj) {
      if (obj[key] !== '') nameArr.push(obj[key]);
    }
    packageName.value = nameArr.join('-');
    newPackageName.value = nameArr.join('-');
    packageBatchNo.value = dateConvert(new Date());
  } else {
    message.warning('请检查是否已选择导入批次或模板！');
  }
};
// 同上一次包装信息
const lastTime = () => {
  if (lastPackageName.value == null && lastPackageBatchNo.value == null) {
    message.info('没有上次的包装信息');
  } else {
    packageName.value = lastPackageName.value;
    packageBatchNo.value = lastPackageBatchNo.value;
  }
};

// 生产新的包装信息
const createNew = () => {
  packageBatchNo.value = dateConvert(new Date());
  packageName.value = newPackageName.value;
};

// 获取模板数据及 ID
const getTemplateInfo = async () => {
  templateId.value = printTemplate.value.slice(
    0,
    printTemplate.value.indexOf('-'),
  );
  allTemplate.value.forEach(item => {
    if (item.id == templateId.value) {
      templateData.value = item.contentX6;
    }
  });
};

// 打印预览
const printPreview = async () => {
  if (printTemplate.value !== '' && queryParams.batchNo !== '') {
    imageVisible.value = true;
    printing.value = false;
    imageUrls.length = 0;
    let tempStr = JSON.stringify(templateData.value);
    const rows = JSON.parse(JSON.stringify(dataSource.value[0]));
    let base64 = await getBase64(rows, tempStr);
    imageUrls.push(base64);
    printing.value = true;
  } else {
    message.warning('请检查是否已选择导入批次或模板！');
  }
};

// 确认打印
const printCard = async data => {
  if (data.length !== 0) {
    printVisible.value = false;
    globalLoading.value = true;
    printing.value = false;
    const formData = new FormData();
    formData.append('customerPrintTemplateId', templateId.value);
    formData.append('packageBatchNo', packageBatchNo.value);
    formData.append('packageName', packageName.value);

    let tempStr = JSON.stringify(templateData.value);
    const rows = JSON.parse(JSON.stringify(data));
    let amount = 0;
    for (let key in rows) {
      amount = amount + 1;
      let base64 = await getBase64(rows[key], tempStr, rows[key].assetNo);
      let file = base64toFile(base64, rows[key].id);
      formData.append('file', file);
      propText.value = `生成中,已生成${amount}张`;
    }
    multipleImageUpload(formData).then(
      successData => {
        if (successData.success === true) {
          message.success('资产生产图片成功');
        } else {
          message.error('资产生产图片失败');
        }
        globalLoading.value = false;
        printing.value = true;
        all.value = false;
        searchPrintInfo();
        clearSelect();
      },
      errorData => {
        Common.processException(errorData);
        globalLoading.value = false;

        printing.value = true;
        all.value = false;
        clearSelect();
      },
    );
  } else {
    all.value = false;
    printVisible.value = false;
    message.warning('请选择打印数据');
  }
};
// 全部生成图片
const printAll = () => {
  all.value = true;
  pager.start = 0;
  pager.length = 10000;
  searchPrintInfo();
  showPrintInfo();
};

//下载全部图片(zip)
const downloadImageZip = () => {
  if (queryParams.batchNo === '') {
    message.warning('请选择导入批次');
  } else {
    globalLoading.value = true;
    var xhr = new XMLHttpRequest();
    xhr.open('get', `api/LabelPrintResource/batchImageDownload?batchNo=${queryParams.batchNo}`, true);
    const token = localStorage.getItem('#token');
    xhr.setRequestHeader('token', token);
    xhr.setRequestHeader('Content-type', 'application/json');
    xhr.responseType = 'blob';
    xhr.onreadystatechange = function(){
      if(xhr.readyState === 4 && xhr.status === 200){
        let res = xhr.response;
        let blob = new Blob([res]);   
        const blobUrl = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.download = '图片.zip';
        link.style.display = 'none';
        link.href = blobUrl;
        document.body.appendChild(link);
        link.click();
        URL.revokeObjectURL(blobUrl);
        document.body.removeChild(link);  
        globalLoading.value = false;
        message.success('下载成功');
      }
    };
    xhr.send();
  }
};

// 打印后清除所有选择
const clearSelect = () => {
  table.value.clear();
};

onMounted(() => {
  init();
  getBase64 = CreateJPEG(hua.value);
  clientId.value = JSON.parse(localStorage.getItem('#LoginInfo')).loginClientId;
});

// 封装通用sqlApi请求函数
const commonSqlApi = (url, data) => {
  clientId.value = JSON.parse(localStorage.getItem('#LoginInfo')).loginClientId;
  let params = { clientId: clientId.value, batchNo: queryParams.batchNo };
  SqlApi.execute(url, params).then(
    successData => {
      if (successData.errorCode == 0) {
        if (successData.lines !== null) {
          data.value = successData.lines.map(item => {
            return (item = { label: item });
          });
          data.value.unshift({ label: '' });
        } else {
          data.value = [];
        }
      } else {
        Notify.error('查询信息异常', successData.errorMessage, true);
      }
    },
    errorData => {
      Common.processException(errorData);
    },
  );
};

// 初始化数据
const init = () => {
  clientId.value = JSON.parse(localStorage.getItem('#LoginInfo')).loginClientId;
  let params = { clientId: clientId.value };
  getTemplate().then(res => {
    allTemplate.value = res.datas;
  });
  // 查询批次号
  SqlApi.execute('20230613_134214', params).then(
    successData => {
      if (successData.errorCode == 0) {
        if (successData.lines !== null) {
          let datas = successData.lines.map(item => {
            return (item = { label: item });
          });
          batchNos.value = datas.reverse();
        }
      } else {
        Notify.error('查询导入批次异常', successData.errorMessage, true);
      }
    },
    errorData => {
      Common.processException(errorData);
    },
  );
  // 查询模板
  SqlApi.execute('20230613_135541', params).then(
    successData => {
      if (successData.errorCode == 0) {
        if (successData.label !== null) {
          templateNames.value = successData.lines;
        }
      } else {
        Notify.error('查询模板信息异常', successData.errorMessage, true);
      }
    },
    errorData => {
      Common.processException(errorData);
    },
  );
  // 获取上一次的包装信息
  SqlApi.execute('20230613_194855', params).then(
    successData => {
      if (successData.errorCode == 0) {
        const { packageName, packageBatchNo } = successData.lines[0];
        lastPackageName.value = packageName;
        lastPackageBatchNo.value = packageBatchNo;
      } else {
        Notify.error('获取包装信息异常', successData.errorMessage, true);
      }
    },
    errorData => {
      Common.processException(errorData);
    },
  );
};
</script>

<style scoped>
.commonStyle {
  margin-right: 16px;
  width: 160px;
}
.search,
.operationBtn {
  margin-top: 8px;
}
.operationBtn {
  display: flex;
  justify-content: space-between;
}
#displayName:disabled {
  background: white;
  color: black;
}
.full-modal .ant-modal {
  max-width: 100%;
  top: 0;
  padding-bottom: 0;
  margin: 0;
}
.full-modal .ant-modal-content {
  display: flex;
  flex-direction: column;
  height: calc(100vh);
}
.full-modal .ant-modal-body {
  flex: 1;
}
</style>