<template>
  <div>
    <div v-show="!isShow">
      <p-card title="主要信息">
        <p-grid-form
          ref="gridForm"
          :span="8"
          :items="items"
          @submit="
            ($event, form) => {
              handleSubmit($event, form, 'formTarget');
            }
          "
        />
        <p-table
          :id="$route.meta.menuId + '_63472'"
          ref="logTable"
          style="margin-top: 10px"
          :columns="tableColumns"
          :rowKey="bizType=='05' ? 'uniqueId' : 'bizId'"
          :expandRowByClick="false"
          :rowSelectFixed="true"
          :dataSource.sync="dataSource"
          :remoteUrl="remoteUrl"
          :remoteData="remoteData"
          :autoLoad="false"
          :loading="tabLoding"
          :scroll="{ x: true }"
          @selectChange="selectChange"
          dragle
          auto-width
          bordered
        >
          <template slot="yzupflag" slot-scope='text, record'>
          {{ text == '1' ? '已上传' : text == '0' ? '未上传' : text }}
          </template>
          <template slot="xsqdupflag" slot-scope='text, record'>
          {{ text == '1' ? '已上传' : text == '0' ? '未上传' : text }}
          </template>
          <template slot="ypupflag" slot-scope='text, record'>
          {{ text == '1' ? '已上传' : text == '0' ? '未上传' : text }}
          </template>
          <template slot="fpupflag" slot-scope='text, record'>
          {{ text == '1' ? '已上传' : text == '0' ? '未上传' : text }}
          </template>
          <template slot="upFlag" slot-scope='text, record'>
           {{ text == '1' ? '已上传' : text == '0' ? '未上传' : text }}
          </template>
          <div slot="action" href="javascript:;" slot-scope="text,record">
            <a slot="action" @click="view(text)">预览</a>
            <a-divider type="vertical" />
            <a slot="action" @click="imgUpload(record)">上传</a>
            <a-divider type="vertical" v-if="record.upFlag == '1'" />
            <a slot="action" v-if="record.upFlag == '1' && bizType != '01'" @click="del(record)">删除</a>
            <a-divider type="vertical" v-if="bizType == '01' && (record.xsqdupflag == '1' || record.ypupflag == '1' || record.fpupflag == '1' || record.yzupflag == '1')" />
            <a slot="action" v-if="bizType == '01' && (record.xsqdupflag == '1' || record.ypupflag == '1' || record.fpupflag == '1' || record.yzupflag == '1')" @click="del(record)">删除</a>
          </div>
        </p-table>
      </p-card>
      <div v-show="false">
        <img width="100%" height="700px" :src="imgUrl" alt="" />
      </div>

      <viewer ref="viewer" class="viewer" @inited="inited" :images="[decImg]" :options="opts">
        <img :src="decImg" style="width: 200px; height: 200px; display: none" />
      </viewer>

      <imgsUpload v-model="isUpload" :isView="lookats" @completed="handleUploadImgs" :uploadIdlist="uploadIdlist"></imgsUpload>

    </div>
    <div>
      <!-- <detail-modal v-show="isShow" @clickEven="clickEven" :resData="resData"></detail-modal> -->
    </div>
  </div>
</template>

<script>
import DetailModal from "./detailModal";
import { formItems, tableColumns1, tableColumns2, tableColumns7, columns, customerCodeColumns, itemColumns2, formItems1, formItems2, formItems3, formItems4, formItems5, formItems6, formItems7 } from "./js/config";
import { upcloud_base_wh_inbound, SERVICE_DATA_API_BASE, upcloud_base_common } from "@/config/serviceSettings";
// import { diffOption } from "@/views/kzyWMS/utils/index.js";
import { bizFileAdd, bizFilePage, bizFileDel, bizFileDown, qnSalesData, print, del } from "./api/index";
import { sorter } from "@/views/kzyWMS/utils/sort.js";
import { getBusiness } from "@/views/kzyWMS/api/business"; // 系统参数接口
import ImgsUpload from "./ImgsUpload";
import "viewerjs/dist/viewer.css";
// import { component } from 'v-viewer'
import VueViewer from "v-viewer";
import Vue from "vue";
Vue.use(VueViewer);
export default {
  components: {
    DetailModal, imgsUpload: ImgsUpload,
  },
  data() {
    
            // const url = URL.createObjectURL(res.data)
    return {
      opts: {
        disabled: "display:none",
        inline: false,
        button: true,
        navbar: false,
        title: false,
        toolbar: false,
        tooltip: false,
        movable: false,
        zoomable: true,
        rotatable: false,
        scalable: false,
        transition: true,
        fullscreen: true,
        keyboard: false,
        // "url": "data-source"
      },
      decImg: "",
      imgUrl: [],
      isUpload: false,
      lookats: false,
      uploadIdlist: [],

      businessData: null,
      items: null,
      tableColumns: sorter(tableColumns1(this)),
      remoteUrl: {
        url: SERVICE_DATA_API_BASE + "/search/page",
        method: "post",
        headers: {
          Authorization: "Bearer " + JSON.parse(localStorage.getItem("token")),
          "content-type": "application/json",
        },
      },
      remoteData: {},
      dataSource: [],
      selectedRows:[],
      bizType: "",
      supType: "",
      tabLoding: false,
      isShow: false,
      detailDis: false,
      resData: {},
    };
  },
  created() {
    // sorter(this.tableColumns).then((res) => {
    //   this.tableColumns = res;
    // });
    getBusiness().then((res) => {
      console.log(res, "resresres");
      this.businessData = res; // 系统参数
      this.items = formItems(this);
      //   var data = {}
      //   if (res == 'kzy') {
      //     data.bizType = '04'
      //   } else {
      //     data.bizType = '01'
      //   }
      //   this.getList(data)
    });
  },
  methods: {
    selectChange(selectedRowKeys, selectedRows) {
      this.selectedRows = selectedRows;
    },
    //根据勾选明细图片打印
    handlePrint() {
      if (this.selectedRows.length < 1) {
        this.$message.warning("请先选择数据");
        return;
      }
      if (this.selectedRows.length > 1) {
        this.$message.warning("打印只能同时勾选一条数据");
        return;
      }
      console.log(this.selectedRows,'this.selectedRows');
      let list = this.selectedRows.map(item => {
        return {id:item.id}
      })
      let par = {
        printBillCode: 'imgManage-pdf',
        params: { id: list[0].id },
        warehouseld: this.$store.state.user.warehouse.warehouseId
      }
      if (this.bizType == '01') {
        if(!this.supType) return this.$message.warn('请选择图片类型!')
        if(this.supType == '09') par.params = { id: list[0].yzbizid }
        if(this.supType == '10') par.params = { id: list[0].xsqdbizid }
        if(this.supType == '11') par.params = { id: list[0].ypbizid }
        if(this.supType == '12') par.params = { id: list[0].fpbizid }
      }
      qnSalesData(par).then(res => {
        console.log(res);
        if (res.success) {
          const printUrl = res.data.printAddress
          print(printUrl, res.data.printData).then(res => {
            if (res.success) {
              this.$message.success('打印成功')
            } else {
              this.$message.error(res.message)
            }
          })
        } else {
          this.$message.error(res.message)
        }
      })
      // let imgUrl1 = [];
      // console.log(this.selectedRows, "selectedRowsselectedRows");
      // this.selectedRows.forEach((t) => {
      //   console.log(t.fileUrl, "t.fileUrlt.fileUrl");
      //   imgUrl1.push(t.fileUrl);
      // });
      // let $app = document.getElementById("app");
      // let $div = document.createElement("div");
      // // $div.classList.add("print-img");
      // // $div.style.height = "100%"
      // let html = "";
      // imgUrl1.forEach((item, index) => {
      //   html += `<iframe id="print" src="${item}" width="0" height="0" />`;
      // });
      // $div.innerHTML = html;
      // document.body.appendChild($div);
      // $app.style.display = "none";
      // window.onafterprint = function (event) {
      //   $app.style.display = "block";
      //   $div.remove();
      // };
      // setTimeout(() => {
      //   window.print();
      // }, 1000);
    },
    //上传
    handleUploadImgs(list) {
      console.log(list,'list');
      console.log(this.resData,'this.resData');
      console.log(this.bizType,'this.bizType');

      let data = {};
      data.bizId = this.resData.bizId;
      data.bizType = this.resData.bizType;
      data.dataType = 0;
      // data.fileName = list[0].name;
      data.fileName = this.bizType == '02' ? this.resData.itemCode : this.resData.itemCode + '_' + this.resData.manufacturerLotNum
      data.relativePath = list[0].path;
      data.fileType = list[0].type;
      data.name = list[0].name;
      data.fileUrl = list[0].path;
      data.fileFolderId = list[0].id;
      let s = list.map((i) => {
        return {
          bizId: this.resData.bizId,
          bizType: this.resData.bizType,
          dataType: 0,
          fileName: this.bizType == '02' ? this.resData.itemCode : this.resData.itemCode + '_' + this.resData.manufacturerLotNum,
          relativePath: i.path,
          fileType: i.type,
          name: this.bizType == '02' ? this.resData.itemCode : this.resData.itemCode + '_' + this.resData.manufacturerLotNum,
          fileUrl: i.path,
          fileFolderId: i.id,
        };
      });
      if (this.bizType == '01') {
        s.forEach(item => {
          item.bizId = this.resData.bizId + "_" + this.supType
          item.bizType = this.supType
        })
      }
      bizFileAdd([...s]).then((res) => {
        if (!res.success) {
          this.$exception(res);
          return false;
        }
        let data = this.$refs.gridForm.form.getFieldsValue()
        this.getList(data);
      });
    },
    // 上传逻辑
    showUploadImgs(record) {
      this.isUpload = true;
    },
    imgUpload(record) {
      if (this.bizType == '01' && !this.supType) {
        this.$message.warn('请选择图片类型!')
        return
      }
      console.log(record, this.bizType);
      record.bizType = this.bizType;
      this.resData = record;
      this.showUploadImgs(this.resData);
    },
    inited(viewer) {
      this.$viewer = viewer;
    },
    del(record) {
      let par = [{
        bizId:record.bizId
      }]
      if (this.bizType == '01' && !this.supType) {
        this.$message.warn('请选择图片类型!')
        return
      } else {
        par = [{
          bizId:record.bizId + '_' + this.supType
        }]
      }
      del(par).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.$refs.logTable.reload()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    view(data) {
      console.log(data);

      this.decImg = data.fileUrl;
      if (this.bizType == '01') {
        if(!this.supType) return this.$message.warn('请选择图片类型!')
        if(this.supType == '09') this.decImg = data.yzfileurl
        if(this.supType == '10') this.decImg = data.xsqdfileurl
        if(this.supType == '11') this.decImg = data.ypfileurl
        if(this.supType == '12') this.decImg = data.fpfileurl
      }
      this.$nextTick(() => {
        // this.$viewer.show();
        if(!this.decImg) return this.$message.error('暂无文件信息')
        window.open(this.decImg)
      });
    },
    //查询事件
    handleSubmit(event, form) {
      event.preventDefault();
      this.detailData = [];
      form.validateFields((error, values) => {
        console.log(values, "values");
        if (!error) {
          this.getList(values);
        }
      });
    },

    getList(data) {
      console.log(data);
      var params = {};
      let bizType = {
        "01": { num: "querySupplierImage", Columns: sorter(tableColumns1(this)), items: formItems1(this) }, //供应商样章
        "02": { num: "queryItemImage", Columns: sorter(tableColumns7(this)), items: formItems7(this) }, //首营
        "05": { num: "rcvReportInfo", Columns: sorter(itemColumns2(this)), items: formItems2(this) }, //质检报告单
        // "03": { num: "rcvDetailInfo", Columns: sorter(columns(this)), items: formItems3(this) }, //随货同行单
        // "04": { num: "rcvDetailInfo", Columns: sorter(columns(this)), items: formItems4(this) }, //温度
        // "05": { num: "rcvReportInfo", Columns: sorter(columns(this)), items: formItems5(this) }, //报告单
        // "06": { num: "queryCustomerImage", Columns: sorter(customerCodeColumns(this)), items: formItems6(this) }, //客户
      };
      this.bizType = data.bizType;

      params = {
        num: bizType[data.bizType].num,

        params: {
          bizType: data.bizType,
          ...data,
        },
      };
      console.log(params);
      this.items = bizType[data.bizType].items;
      this.tableColumns = bizType[data.bizType].Columns;
      this.$nextTick(() => {
        this.$refs.gridForm.form.validateFields((error, values) => {
          console.log(values, "values");
          params.params = { ...params.params, ...values };
          this.tabLoding = true;
          this.remoteData = params;
        });
      });

      return;
      if (data.bizType === "01") {
        console.log(tableColumns1(this));
        this.tableColumns = tableColumns1(this);
        params = {
          num: "supplierInfo",
          params: {
            bizType: data.bizType,
            ...data,
          },
        };
      } else if (data.bizType === "02") {
        this.tableColumns = tableColumns2(this);
        params = {
          num: "itemInfo",
          params: {
            bizType: data.bizType,
            ...data,
          },
        };
      } else if (data.bizType === "05") {
        this.tableColumns = columns(this);
        params = {
          num: "rcvReportInfo",
          params: {
            bizType: data.bizType,
            ...data,
          },
        };
      } else if (data.bizType === "03") {
        this.tableColumns = columns(this);
        params = {
          num: "rcvDetailInfo",
          params: {
            bizType: data.bizType,
            ...data,
          },
        };
      } else if (data.bizType === "04") {
        this.tableColumns = columns(this);
        params = {
          num: "rcvDetailInfo",
          params: {
            bizType: data.bizType,
            ...data,
          },
        };
      }
      this.tabLoding = true;
      this.remoteData = params;
      // getList(params).then((res) => {
      //   this.tabLoding = false
      //   if (!res.success) {
      //     this.$exception(res)
      //     return false
      //   }
      //   this.dataSource = res.data.list
      // })
    },

    edit(text) {
      this.isShow = true;
      console.log(text, this.bizType);
      text.bizType = this.bizType;
      this.resData = text;
    },
    clickEven() {
      this.isShow = false;
      this.tabLoding = false;
      this.$nextTick(() => {
        this.$refs.gridForm.form.setFieldsValue({
          bizType: this.bizType,
        });
      });
    },
  },
};
</script>
<style lang="less" scoped>
@media print {
  @page {
    height: auto !important;
    margin: 0; // 可以控制打印布局（四周边距）
  }
  body{
    height: inherit;
  }
  .print-img {
    // background-color: red;
    height: 100%;
    width: 100%;
    // font-size: 20px;
    // color: green;
  }
}
</style>
