<template>
  <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="searchPrintInfo"
      />
      <label>保管人员：</label>
      <a-select
        v-model:value="queryParams.depositoryUser"
        show-search
        class="commonStyle"
        :options="depositoryUsers.map((item) => ({ value: item.label }))"
        @change="searchPrintInfo"
      />
      <label>打印状态：</label>
      <a-select
        v-model:value="status"
        show-search
        class="commonStyle"
        :options="
          statusOptions.map((item) => ({
            value: `${item.value}-${item.label}`,
            label: item.label,
          }))
        "
        @change="searchPrintInfo"
      />
    </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="searchPrintInfo"
      />
      <label>所属部门：</label>
      <a-select
        v-model:value="queryParams.organizationName"
        show-search
        class="commonStyle"
        :options="organizationNames.map((item) => ({ value: item.label }))"
        @change="searchPrintInfo"
      />
      <label>成本中心：</label>
      <a-select
        v-model:value="queryParams.costCenterName"
        show-search
        class="commonStyle"
        :options="costCenterNames.map((item) => ({ value: item.label }))"
        @change="searchPrintInfo"
      />
      <a-button type="primary" @click="searchPrintInfo">查询</a-button>
    </div>
    <div style="margin: 8px 0 0 9px">
      <label>打印模板：</label>
      <a-select
        v-model:value="printTemplate"
        show-search
        class="commonStyle"
        :options="
          templateNames.map((item) => ({
            value: `${item.id}-${item.name}`,
            label: item.name,
          }))
        "
      />
      <a-button
        type="dashed"
        style="margin-right: 16px"
        @click="imageVisible = true"
      >
        打印预览
      </a-button>
      <a-button type="dashed" style="margin-right: 16px" @click="showPrintInfo">
        打印
      </a-button>
    </div>
    <a-divider />
    <CommonTable
      :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="record.imageUrl" />
        </template>
      </template>
    </CommonTable>
    <a-modal
      v-model:visible="printVisible"
      title="包装信息"
      ok-text="确认"
      cancel-text="取消"
      @ok="printCard"
    >
      <label>包装批号：</label>
      <a-input
        id="displayName"
        v-model:value="packageBatchNo"
        :disabled="true"
      />
      <label>上次的批号：</label>
      <a-input
        id="displayName"
        v-model:value="lastPackageBatchNo"
        :disabled="true"
      />
      <label>包装名称：</label>
      <a-input id="displayName" v-model:value="packageName" :disabled="true" />
      <label>上次的名称：</label>
      <a-input
        id="displayName"
        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="打印预览"
      ok-text="确认"
      cancel-text="取消"
      :body-style="bodyStyle"
      @ok="imageVisible = false"
    >
      <a-image
        :preview="{ visible: false }"
        :width="200"
        class="image"
        :src="imageUrls[0]"
        @click="visible = true"
      />
      <div style="display: none">
        <a-image-preview-group
          :preview="{ visible, onVisibleChange: (vis) => (visible = vis) }"
        >
          <a-image v-for="item in imageUrls" :key="item" :src="item" />
        </a-image-preview-group>
      </div>
    </a-modal>
    <div ref="hua" style="float: left; z-index: -999" />
    <Loading v-if="globalLoading" />
  </div>
</template>

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

const imageUrls = reactive([
  'https://gw.alipayobjects.com/zos/antfincdn/LlvErxo8H9/photo-1503185912284-5271ff81b9a8.webp',
  'https://gw.alipayobjects.com/zos/antfincdn/cV16ZqzMjW/photo-1473091540282-9b846e7965e3.webp',
  'https://gw.alipayobjects.com/zos/antfincdn/x43I27A55%26/photo-1438109491414-7198515b166b.webp',
]);
const total = ref(0);
const isSelect = ref(true);
const isLoading = ref(false);
const selectedRows = ref([]);
const dataSource = ref([]);
const printVisible = ref(false);
const imageVisible = ref(false);
const visible = ref(false);
const globalLoading = ref(false);
const bodyStyle = {
  display: 'flex',
  justifyContent: 'center',
};
const status = ref('');
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([]);
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);
let getImageData;
// 获取分页
const getPageParams = (start, length) => {
  pager.start = (start - 1) * length;
  pager.length = length;
  searchPrintInfo();
};
// 查询信息
const searchPrintInfo = () => {
  isLoading.value = true;
  if (status.value !== undefined) {
    queryParams.labelPrintType = status.value.slice(
      0,
      status.value.indexOf('-'),
    );
  }
  let params = { ...queryParams, ...pager };
  if (queryParams.batchNo !== '') {
    SqlApi.execute('20230613_140456', params).then(
      successData => {
        const { lines, errorMessage, errorCode } = successData;
        if (errorCode == 0) {
          total.value = successData.total;
          lines.forEach(item => {
            item.key = item.id;
          });
          dataSource.value = lines;
          isLoading.value = false;
        } else {
          Notify.error('查询异常', errorMessage, true);
        }
        isLoading.value = false;
      },
      errorData => {
        Common.processException(errorData);
        isLoading.value = false;
      },
    );
  } else {
    message.error('请选择导入批次');
    status.value = '';
    dataSource.value = [];
    queryParams.clientName = '';
    queryParams.costCenterName = '';
    queryParams.depositoryUser = '';
    queryParams.organizationName = '';
    isLoading.value = false;
  }
};
// 获取所选项的数据
const selectColumn = rows => {
  selectedRows.value = rows;
  console.log('onSelectChange', selectedRows.value);
};
// 展开打印框
const showPrintInfo = () => {
  if (printTemplate.value !== '') {
    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.error('请选择打印模板');
  }
};
// 同上一次包装信息
const lastTime = () => {
  if (lastPackageName.value == null && lastPackageBatchNo.value == null) {
    message.info('没有上次的包装信息');
  } else {
    packageName.value = lastPackageName.value;
    packageBatchNo.value = lastPackageBatchNo.value;
  }
};

// const base64toFile = (url, imageName) => {
//   const arr = url.split(',');
//   const mime = arr[0].match(/.*?:(.*?);/)[1];
//   const suffix = mime.split('/')[1];
//   const bstr = window.atob(arr[1]);
//   let n = bstr.length;
//   const u8arr = new Uint8Array(n);
//   while (n--) {
//     u8arr[n] = bstr.charCodeAt(n);
//   }
//   return new File([u8arr], `${imageName}.${suffix}`, {
//     type: 'multipart/form-data',
//   });
// };

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

// 确认打印
const printCard = () => {
  globalLoading.value = true;
  const formData = new FormData();
  templateId.value = printTemplate.value.slice(
    0,
    printTemplate.value.indexOf('-'),
  );
  allTemplate.value.forEach(item => {
    if (item.id == templateId.value) {
      templateData.value = JSON.stringify(item.contentX6);
    }
  });

  selectedRows.value.forEach(async item => {
    item.number = item.assetNo;
    item.name = item.assetName;
    item.unit = item.depositoryUser;
    item.keeper = item.organizationName;
    item.EPC = item.depositoryUser;
    item.BarCode =
      'https://rfid.fa.sjtu.edu.cn/c/5C5CFA24F72542B8910F247BA014DDBB';
    let base64 = await getImageData(item, templateData.value);
    console.log('图片base64：',base64);
  });

  formData.append('customerPrintTemplateId', templateId.value);
  formData.append('packageBatchNo', packageBatchNo.value);
  formData.append('packageName', packageName.value);
  // formData.append('file', file);

  multipleImageUpload(formData).then(
    successData => {
      if (successData.success === true) {
        message.success('资产生产图片成功');
      } else {
        message.error('资产生产图片失败');
      }
      globalLoading.value = false;
      printVisible.value = false;
      searchPrintInfo();
    },
    errorData => {
      Common.processException(errorData);
      globalLoading.value = false;
      printVisible.value = false;
    },
  );
};

onMounted(() => {
  init();
  getImageData = CreateJPEG(hua.value);
});

// 封装通用sqlApi请求函数
const commonSqlApi = (url, data) => {
  SqlApi.execute(url).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 {
        Notify.error('查询信息异常', successData.errorMessage, true);
      }
    },
    errorData => {
      Common.processException(errorData);
    },
  );
};

// 初始化数据
const init = () => {
  getTemplate().then(res => {
    allTemplate.value = res.datas;
    console.log(res);
  });
  commonSqlApi('20230613_192444', depositoryUsers); // 查询保管人
  commonSqlApi('20230613_193808', clientNames); // 查询公司
  commonSqlApi('20230613_194108', organizationNames); // 查询部门
  commonSqlApi('20230613_194557', costCenterNames); // 查询成本中心
  // 查询批次号
  SqlApi.execute('20230613_134214').then(
    successData => {
      if (successData.errorCode == 0) {
        if (successData.lines !== null) {
          batchNos.value = successData.lines.map(item => {
            return (item = { label: item });
          });
        }
      } else {
        Notify.error('查询导入批次异常', successData.errorMessage, true);
      }
    },
    errorData => {
      Common.processException(errorData);
    },
  );
  // 查询模板
  SqlApi.execute('20230613_135541').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').then(
    successData => {
      if (successData.errorCode == 0) {
        const { packageName, packageBatchNo } = successData.lines;
        lastPackageName.value = packageName;
        lastPackageBatchNo.value = packageBatchNo;
      } else {
        Notify.error('获取包装信息异常', successData.errorMessage, true);
      }
    },
    errorData => {
      Common.processException(errorData);
    },
  );
};
</script>

<style scoped>
.printDiv {
  padding: 24px;
}
.commonStyle {
  margin-right: 16px;
  width: 160px;
}
.search,
.operationBtn {
  margin-top: 8px;
}
.operationBtn {
  display: flex;
  justify-content: space-between;
}
#displayName:disabled {
  background: white;
  color: black;
}
</style>