<template>
  <div>
    <el-card class="el-card">
      <el-form :model="filterQuery" class="query-form" size="mini" label-width="100px"  v-if="showSearch">
        <el-row style=" display:flex;  flex-wrap: wrap; ">

          <el-col :span="8">
            <el-form-item class="query-form-item"  label="当前仓库:">
              <el-select v-model="filterQuery.invCode" placeholder="请选择当前仓库" clearable="true"
                         size="mini"
                         style="width: 90%"
              >
                <el-option
                  v-for="item in invListAllFlagInv"
                  :key="item.code"
                  :label="item.label"
                  :value="item.code">
                  <span style="float: left">{{ item.label }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

<!--          <el-col :span="8">-->
<!--            <el-form-item class="query-form-item"  label="往来仓库:">-->
<!--              <el-select v-model="filterQuery.fromInvCode" placeholder="请选择往来仓库" clearable="true"-->
<!--                         size="mini"-->
<!--                         style="width: 90%"-->
<!--              >-->
<!--                <el-option-->
<!--                  v-for="item in invList"-->
<!--                  :key="item.code"-->
<!--                  :label="item.label"-->
<!--                  :value="item.code">-->
<!--                  <span style="float: left">{{ item.label }}</span>-->
<!--                </el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->

<!--          <el-col :span="8">-->
<!--            <el-form-item class="query-form-item" label="往来单位:" label-width="100px">-->
<!--              <el-select-->
<!--                v-model="filterQuery.fromCorp"-->
<!--                filterable-->
<!--                remote-->
<!--                clearable="true"-->
<!--                reserve-keyword-->
<!--                placeholder="请输入往来单位名称"-->
<!--                :remote-method="findMethod"-->
<!--                size="mini"-->
<!--                style="width: 90%"-->
<!--                :loading="loading"-->
<!--              >-->
<!--                <el-option-->
<!--                  v-for="item in fromOptions"-->
<!--                  :key="item.code"-->
<!--                  :label="item.label"-->
<!--                  :value="item.code"-->
<!--                >-->
<!--                  <span style="float: left">{{ item.label }}</span>-->
<!--                </el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->

<!--          <el-col :span="8">-->
<!--            <el-form-item class="query-form-item" label="出入库类型:">-->
<!--              <el-select v-model="filterQuery.mainAction" placeholder="请选择出入库类型" style="width: 90%" @change="changeActionType">-->
<!--                <el-option label="入库" value="WareHouseIn"></el-option>-->
<!--                <el-option label="出库" value="WareHouseOut"></el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->

<!--          <el-col :span="8">-->
<!--            <el-form-item class="query-form-item" label="单据类型:" label-width="100px" >-->
<!--              <el-select-->
<!--                v-model="filterQuery.action"-->
<!--                filterable-->
<!--                remote-->
<!--                clearable="true"-->
<!--                reserve-keyword-->
<!--                placeholder="请输入单据类型"-->
<!--                size="mini"-->
<!--                style="width: 90%"-->
<!--              >-->
<!--                <el-option-->
<!--                  v-for="item in actions"-->
<!--                  :key="item.code"-->
<!--                  :label="item.label"-->
<!--                  :value="item.code"-->
<!--                >-->
<!--                  <span style="float: left">{{ item.label }}</span>-->
<!--                </el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->

          <el-col :span="8">
            <el-form-item class="query-form-item" label="耗材类型:">
              <el-select v-model="filterQuery.hcType" placeholder="请选择耗材类型" style="width: 90%" clearable="true">
                <el-option label="高耗" :value=1></el-option>
                <el-option label="普耗" :value=2></el-option>
              </el-select>
            </el-form-item>
          </el-col>



          <el-col :span="8">
            <el-form-item class="query-form-item" label="出入库时间:">
              <el-date-picker
                :picker-options="pickerOptions"
                v-model="actDateRange"
                type="daterange"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 90%"
              ></el-date-picker>
            </el-form-item>
          </el-col>


<!--          <el-col :span="8">-->
<!--            <el-form-item class="query-form-item" label="发票确认时间:">-->
<!--              <el-date-picker-->
<!--                :picker-options="pickerOptions"-->
<!--                v-model="confirmDateRange"-->
<!--                type="daterange"-->
<!--                format="yyyy 年 MM 月 dd 日"-->
<!--                value-format="yyyy-MM-dd"-->
<!--                range-separator="至"-->
<!--                start-placeholder="开始日期"-->
<!--                end-placeholder="结束日期"-->
<!--                style="width: 90%"-->
<!--              ></el-date-picker>-->
<!--            </el-form-item>-->
<!--          </el-col>-->


        </el-row>
      </el-form>
            <div class="top-right-btn">
        <el-button-group>
          <el-button icon="el-icon-view" type="primary" @click="hideSearch">显示/隐藏搜索栏</el-button>
          <el-button
            type="primary"
            icon="el-icon-refresh"
            @click="onReset"
          >重置
          </el-button>
          <el-button type="primary" icon="el-icon-search" @click="onSubmit"
          >查询
          </el-button
          >
<!--          <el-button type="primary" icon="el-icon-document" @click="selectExport" :loading="selectExportLoading">选中导出Excel</el-button>-->
<!--          <el-button type="primary" icon="el-icon-document" @click="searchExport" :loading="searchExportLoading">结果导出Excel</el-button>-->
          <el-button type="primary" icon="el-icon-printer" @click="optinPrint" :loading="optinPrintLoading">选中打印</el-button>
          <el-button type="primary" icon="el-icon-printer" @click="selectPrint" :loading="selectPrinttLoading">查询结果打印</el-button>
        </el-button-group>
      </div>
      <el-divider style="margin: 15px"></el-divider>
      <el-table v-loading="loading" :data="list" style="width: 100%" border highlight-current-row borderv
                @selection-change="handleCheckedChange"  :row-style="{ height: '32px' }">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="产品名称" prop="coName" show-overflow-tooltip  width="240"></el-table-column>
        <el-table-column label="规格型号" prop="spec" show-overflow-tooltip  width="300"></el-table-column>
        <el-table-column label="单位" prop="measname" show-overflow-tooltip  width="80"></el-table-column>
        <el-table-column label="总出库数量" prop="count" show-overflow-tooltip  width="120"></el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click.native.stop="detailDialog(scope.row)"
            >详情
            </el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :limit.sync="filterQuery.limit"
        :page.sync="filterQuery.page"
        @pagination="getList"
      ></pagination>
    </el-card>

    <el-dialog
      title="库存详情"
      :visible.sync="detailDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="85%"
      v-if="detailDialogVisible"
    >
      <invProductsDetail
        :inputQuery="this.detailDialogQuery"
        v-on:closeDetailDialog="closeDetailDialog"
      ></invProductsDetail>
    </el-dialog>

  </div>

</template>

<script>
import invProductsDetail from "@/views/inventory/InvProductsOutDetail.vue";
import {
  getResultOrderDeptList,
  getResultOrderList,
  getResultProductOutList,
  verifyTemplateFile,
  printOrderDept,
  printOrderDeptSup,
  excelInoutImport, postExcelInoutImport
} from '@/api/inout/orderDetailResult'
import {getCorrespondence,getBasicUnitMaintainsOptimize} from "@/api/basic/basicUnitMaintain";
import {
  getHead,executeFuc
} from "@/utils/customConfig";
import {getDeptListByUser} from "@/api/auth/authDept";
import {filterSubAllOptimize} from "@/api/system/invSubWarehouse";
import {getOrderDetailBusOptimize} from "@/api/basic/busType";

export default {
  components: {
    invProductsDetail
  },
  name: "supInoutSearchOrder",
  data() {
    return {
      detailDialogVisible: false,
      showSearch: true,
      list: [],
      busTypeOptions: [],
      filterQuery: {
        id: "",
        orderIdFk: null,
        invCode: null,
        fromCorp: null,
        hcType: 2,
        fromCorpName: null,
        coName: null,
        spec: null,
        batchNo: null,
        page: 1,
        limit: 30,
        startAduditTime: null,
        endAduditTime: null,
        action: null,
        actionType: null,
        fromInvCode: null,
        keyWords: null,
        inoutPrintStatus: null,
        confirmStarTime:null,  //发票确认起始日期
        confirmEndTime:null,
        corpName:null,
        mainAction:"WareHouseOut",
      },

      printMap: {
        0: "未打印",
        1: "已打印",
        null: "未打印",
      },

      fromOptions: [],
      actions:[],
      loading: false,
      selectExportLoading: false,
      searchExportLoading: false,
      optinPrintLoading: false,
      selectPrinttLoading: false,
      total: 0,
      tableHeader:[],
      queryList:[],
      fromList:[],
      options: {
        getBusTypeByInv:[],
      },
      detailDialogQuery: {
      },
      orderSelection: [],
      showSup: false,
      customerId: this.$store.getters.customerId,
      map:{
        "actDateRange" : this.actDateRange,
        "confirmDateRange" : this.confirmDateRange,
      },
      invList: [],
      invListAllFlagInv: [],
      deptList: [],
      actDateRange: [],
      confirmDateRange:[],
      actionType: null,
      auditDateRange: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  methods: {
    detailDialog(row) {
        this.detailDialogQuery = {
        code: row.code,
        relId: row.bindRlFk,
        cpmctymc: row.coName,
        nameCode: row.nameCode,
        batchNo: row.batchNo,
        ggxh: row.spec,
        productionDate: row.productionDate,
        expireDate: row.expireDate,
        supId: row.supId,
        deptCode: row.deptCode,
        invCode: this.filterQuery.invCode,
        invSpaceCode: row.invSpaceCode,
        price: row.price,
          hcType: this.filterQuery.hcType
      }

      this.detailDialogVisible = true;
    },
    closeDetailDialog() {
      this.detailDialogVisible = false;
    },
    getInvList() {
      filterSubAllOptimize()
        .then((response) => {
          this.invList = response.data || [];
        })
        .catch(() => {
        });
    },
    getInvListAllFlagInv() {
      filterSubAllOptimize({allFlagInvType:true})
        .then((response) => {
          this.invListAllFlagInv = response.data || [];
          if (this.invListAllFlagInv.length > 0){
            this.filterQuery.invCode = this.invListAllFlagInv[0].code
          }
        })
        .catch(() => {
        });
    },
    getDeptList() {
      getDeptListByUser().then((res) => {
        this.deptList = res.data || [];
      });
    },
    onReset() {
      this.$router.push({
        path: "",
      });
      this.filterQuery = {
        id: "",
        orderIdFk: null,
        invCode: null,
        fromCorp: null,
        hcType: 2,
        fromCorpName: null,
        coName: null,
        spec: null,
        batchNo: null,
        page: 1,
        limit: 30,
        startAduditTime: null,
        endAduditTime: null,
        action: null,
        actionType: null,
        fromInvCode: null,
        keyWords: null,
        inoutPrintStatus: null,
        confirmStarTime:null,  //发票确认起始日期
        confirmEndTime:null,
        corpName:null,
        mainAction:"WareHouseOut",
      };
      this.actDateRange = []
      this.auditDateRange2 = []
      this.getList();
    },
    handleCheckedChange(val) {
      this.orderSelection = val;
    },

    onSubmit() {

      if (this.actDateRange !== null) {
        this.filterQuery.startAduditTime = this.actDateRange[0];
        this.filterQuery.endAduditTime = this.actDateRange[1];
      } else {
        this.filterQuery.startAduditTime = null;
        this.filterQuery.endAduditTime = null;
      }
      if (this.confirmDateRange!== null) {
        this.filterQuery.confirmStarTime = this.confirmDateRange[0];
        this.filterQuery.confirmEndTime = this.confirmDateRange[1];
      } else {
        this.filterQuery.confirmStarTime = null;
        this.filterQuery.confirmEndTime = null;
      }
      this.filterQuery.page = 1;

      if (this.filterQuery.invCode == null) {
        return this.$message.error("请选择当前仓库！");
      }

      this.getList();
    },

    statusFilterType(status) {
      const statusMap = {
        null: "",
        1: "success",
        0: "warning",
      };
      return statusMap[status];
    },

    hideSearch() {
      this.showSearch = !this.showSearch;
    },

    //根据仓库,用户获取单据类型
    getBusTypeByInv() {
      let query = {
        enabled: true,
        detailType: this.actionType,
        mainAction: this.filterQuery.mainAction
      };
      getOrderDetailBusOptimize(query)
        .then((response) => {
          this.actions = response.data.list || [];
        })
        .catch(() => {
        });
    },

    getList() {
      this.loading = true;
      this.filterQuery.actionType = this.actionType;
      // if (this.filterQuery.actionType == 'preInDetail') {
      //   this.filterQuery.invCode = '1000001'
      // } else if (this.filterQuery.actionType == 'preDetail') {
      //   this.filterQuery.invCode = '1000002'
      // }
      getResultProductOutList(this.filterQuery)
        .then((response) => {
          if (response.code === 20000) {
            this.list = response.data.list || [];
            this.total = response.data.total || 0;
          } else {
            this.$message.error(response.message);
          }
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
          this.list = [];
          this.total = 0;
        });
    },
    findMethod(query) {
      this.fromOptions = [];
      let cQuery = {
        key: query,
      };
      getBasicUnitMaintainsOptimize(cQuery)
        .then((response) => {
          this.loading = false;
          this.fromOptions = response.data.list || [];
        })
        .catch(() => {
          this.loading = false;
          this.fromOptions = [];
        });
    },
    changeActionType(){
      this.getBusTypeByInv()
    },
    optinPrint() {
      this.$confirm("是否确定打印选中仓库出入库信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (this.orderSelection == null || this.orderSelection.length <= 0) {
            return this.$message.error("请选择打印的明细！");
          }
          let query = {id: 9};
          this.optinPrintLoading = true
          verifyTemplateFile(query).then((res) => {
            this.optinPrintLoading = false
            if (res.code === 20000) {
              let printParams = {
                mainAction :this.filterQuery.mainAction,
                fromInvCode :this.filterQuery.fromInvCode,
                startAduditTime :this.filterQuery.startAduditTime,
                endAduditTime: this.filterQuery.endAduditTime,
                confirmStarTime : this.filterQuery.confirmStarTime ,
                confirmEndTime : this.filterQuery.confirmEndTime ,
                corpName : this.filterQuery.corpName ,
                employeeName: this.$store.getters.user.employeeName,
                locInvName:this.$store.getters.locInvName,
                templateId: res.data,
                list: this.orderSelection
              };
              printOrderDeptSup(printParams).then((response) => {
                //将pdf文件转换为url。
                const binaryData = [];
                binaryData.push(response);
                //获取blob链接。
                let url = window.URL.createObjectURL(
                  new Blob(binaryData, {type: "application/pdf"})
                );
                this.loading = false;
                window.open(url);//打开新标签页，预览pdf。
              })
            } else {
              this.optinPrintLoading = false
              return this.$message.error(res.message);
            }
          }).catch((error) => {
            this.optinPrintLoading = false
            this.loading = false;
            this.$message.error(error.message);
          })
        })
        .catch(() => {
        });


    },
    selectPrint() {
      this.$confirm("是否确定打印所有查询结果数据", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {

          let query = {id: 9};
          this.selectPrinttLoading = true
          verifyTemplateFile(query).then((res) => {
            this.selectPrinttLoading = false
            if (res.code === 20000) {
              let printParams = {
                templateId: res.data,
                orderIdFk: this.filterQuery.orderIdFk,
                fromInvCode: this.filterQuery.fromInvCode,
                invCode: this.filterQuery.invCode,
                nameCode: this.filterQuery.nameCode,
                coName: this.filterQuery.coName,
                spec: this.filterQuery.spec,
                batchNo: this.filterQuery.batchNo,
                zczbhhzbapzbh: this.filterQuery.zczbhhzbapzbh,
                manufacturer: this.filterQuery.manufacturer,
                actionType: this.filterQuery.actionType,
                keyWords: this.filterQuery.keyWords,
                mainAction: this.filterQuery.mainAction,
                action: this.filterQuery.action,
                locInvName:this.$store.getters.locInvName,
                employeeName: this.$store.getters.user.employeeName,
              };
              if (this.actDateRange !== null) {
                printParams.startAduditTime = this.actDateRange[0];
                printParams.endAduditTime = this.actDateRange[1];
              } else {
                printParams.startAduditTime = null;
                printParams.endAduditTime = null;
              }
              if (this.confirmDateRange!== null) {
                printParams.confirmStarTime = this.confirmDateRange[0];
                printParams.confirmEndTime = this.confirmDateRange[1];
              } else {
                printParams.confirmStarTime = null;
                printParams.confirmEndTime = null;
              }
              printOrderDeptSup(printParams).then((response) => {
                //将pdf文件转换为url。
                const binaryData = [];
                binaryData.push(response);
                //获取blob链接。
                let url = window.URL.createObjectURL(
                  new Blob(binaryData, {type: "application/pdf"})
                );
                this.loading = false;
                window.open(url);//打开新标签页，预览pdf。
              })
            } else {
              this.$message.error(res.message);
              return
            }
          }).catch((error) => {
            this.selectPrinttLoading = false
            this.loading = false;
            this.$message.error(error.message);
          })

        })
        .catch(() => {
        });
      return;


    },

    selectExport() {
      this.$confirm("是否确定导出选中出入库明细, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (this.orderSelection == null || this.orderSelection.length <= 0) {
            return this.$message.error("请选择需要导出的明细！");
          }
          let printParams = {
            list: this.orderSelection
          };
          this.selectExportLoading = true
          postExcelInoutImport(printParams).then((response) => {
            this.selectExportLoading = false
            let blob = new Blob([response], {type: "application/vnd.ms-excel"});
            let url = window.URL.createObjectURL(blob); // 创建一个临时的url指向blob对象
            let a = document.createElement("a");
            a.href = url;
            a.click();
            this.$message.success("成功")
          }).catch(() => {
            this.selectExportLoading = false
          })
        });


    },
    searchExport() {
      this.$confirm("是否确定导出所有查询结果数据", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {

          let printParams = {
            orderIdFk: this.filterQuery.orderIdFk,
            nameCode: this.filterQuery.nameCode,
            coName: this.filterQuery.coName,
            spec: this.filterQuery.spec,
            batchNo: this.filterQuery.batchNo,
            zczbhhzbapzbh: this.filterQuery.zczbhhzbapzbh,
            manufacturer: this.filterQuery.manufacturer,
            actionType: this.filterQuery.actionType,
            keyWords: this.filterQuery.keyWords,
            mainAction: this.filterQuery.mainAction,
            action: this.filterQuery.action
          };

          if (this.filterQuery.actionType == 'preInDetail') {
            printParams.invCode = '1000001'
          } else if (this.filterQuery.actionType == 'preDetail') {
            printParams.invCode = '1000002'
          }

          if (this.actDateRange !== null) {
            printParams.startAduditTime = this.actDateRange[0];
            printParams.endAduditTime = this.actDateRange[1];
          } else {
            printParams.startAduditTime = null;
            printParams.endAduditTime = null;
          }
          if (this.confirmDateRange!== null) {
            printParams.confirmStarTime = this.confirmDateRange[0];
            printParams.confirmEndTime = this.confirmDateRange[1];
          } else {
            printParams.confirmStarTime = null;
            printParams.confirmEndTime = null;
          }
          this.searchExportLoading = true
          excelInoutImport(printParams).then((response) => {
            this.searchExportLoading = false
            let blob = new Blob([response], {type: "application/vnd.ms-excel"});
            let url = window.URL.createObjectURL(blob); // 创建一个临时的url指向blob对象
            let a = document.createElement("a");
            a.href = url;
            a.click();
            this.$message.success("成功")
          })

        });
    },
    executeFuc(row,type,clickFuc,value){
      return executeFuc(this,row,type,clickFuc,value);
    },
    executeEval(row,expression,defaultRet){
      if(expression){
        return eval(expression);
      }
      return defaultRet;
    }
  },
  mounted() {
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
    };
  }
  ,
  created() {
    this.actionType = 'norDetail';
    this.getList();
    // this.getInvList();
    this.getInvListAllFlagInv();
    // this.getBusTypeByInv();
  }
  ,
}
;
</script>

<style type="text/scss" lang="scss">
</style>

