<template>
  <div>
    <el-card class="el-card">
      <el-form :model="filterQuery" class="query-form" label-width="100px" v-if="showSearch">
        <el-row>
          <el-col :span="8">
            <el-form-item label="申购单号">
              <el-input v-model="filterQuery.billNo" style="width: 90%" placeholder="请输入单据号" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="申购仓库:">
              <el-select v-model="filterQuery.invCode" placeholder="请选择申购仓库" @change="getInvList"
                         style="width: 90%">
                <el-option
                  v-for="item in invList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                >
                  <span style="float: left">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="到货部门">
              <el-select v-model="filterQuery.targetDeptCode" clearable @change="getInvList" placeholder="请选择申购部门"
                         style="width: 90%">
                <el-option
                  v-for="item in deptList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                >
                  <span style="float: left">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="到货仓库">
              <el-select v-model="filterQuery.targetInvCode" style="width: 90%" clearable placeholder="请选择所属仓库">
                <el-option
                  v-for="item in targetInvList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.code">
                  <span style="float: left">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="紧急程度：" prop="emergency">
              <el-select v-model="filterQuery.emergency" placeholder="请选择紧急程度" style="width: 90%" clearable>
                <el-option label="正常" :value=1></el-option>
                <el-option label="较急" :value=2></el-option>
                <el-option label="特急" :value=3></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建时间:">
              <el-date-picker
                :picker-options="pickerOptions"
                v-model="actDateRange"
                type="daterange"
                format="yyyy 年 MM 月 dd 日"
                style="width: 90%"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审核时间:">
              <el-date-picker
                :picker-options="pickerAuditOptions"
                v-model="actAuditDateRange"
                type="daterange"
                format="yyyy 年 MM 月 dd 日"
                style="width: 90%"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="top-right-btn">
        <el-button-group style="display:flex;">
          <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="onSubmitFind">查询</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
                @current-change="handleDetail"
                :default-sort="defaultSort" @sort-change="handleSortChange">
        <el-table-column label="序号" type="index" width="60"></el-table-column>
        <el-table-column label="申购单号" prop="billNo"></el-table-column>
        <el-table-column label="到货部门" prop="targetDeptName"></el-table-column>
        <el-table-column label="到货仓库" prop="targetInvName"></el-table-column>
        <el-table-column label="申购仓库" prop="invName"></el-table-column>
        <el-table-column label="紧急程度" prop="emergency">
          <template slot-scope="scope">
            {{ emergencyMap[scope.row.emergency] }}
          </template>
        </el-table-column>
        <el-table-column label="到货截止" prop="arrivalTime"></el-table-column>
        <el-table-column label="创建时间" prop="createTime"
                         sortable="custom" :sort-orders="['ascending', 'descending']"></el-table-column>
        <el-table-column label="审核时间" prop="auditTime"
                         sortable="custom" :sort-orders="['ascending', 'descending']"></el-table-column>
        <el-table-column label="审核人" prop="auditByName"></el-table-column>

        <el-table-column label="审核状态" prop="status">
          <template slot-scope="scope">
            <el-tag :type="(scope.row.status) | statusFilterType">
              {{ statusMap[scope.row.status] }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="90">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click.native.stop="printOrder(scope.row)">打印</el-button>
            <el-button type="text" @click.native.stop="deleteDialog(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

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

    </el-card>
    <el-card class="el-card">
      <el-table v-loading="loading" :data="detailList" style="width: 100%" border>
        <el-table-column label="序号" type="index" width="60"></el-table-column>
        <el-table-column label="DI/物资编码" prop="nameCode"></el-table-column>
        <el-table-column label="物资名称" prop="productName" show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="规格型号" prop="spec" show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="计量单位" prop="measname" show-overflow-tooltip="true" width="100"></el-table-column>
        <el-table-column label="申购数量" prop="count"></el-table-column>
        <el-table-column label="注册/备案号" prop="zczbhhzbapzbh"></el-table-column>
        <el-table-column label="生产厂家" prop="manufactory"></el-table-column>
        <el-table-column label="供应商" prop="supName"></el-table-column>
      </el-table>
    </el-card>


    <el-dialog
      :title="formMap[formName]"
      :visible.sync="newSpDistributionVisible"
      width="80%"
      v-if="newSpDistributionVisible"
      @close='closeDialog'
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <pureApplyDetail
        :closeDialog="closeDialog"
        :idQuery="idQuery"
        :editType="editType"
      ></pureApplyDetail>
    </el-dialog>
  </div>
</template>
<script>
import pureApplyDetail from "./pureApplyDetailDialog";
import {delApply, auditOrder, listApplyDetail, auditListApply, listApply, printOrder} from "@/api/purchase/purApply";
import {getInvListByUser} from "@/api/system/invWarehouse";
import {filterDepts, getDeptListByUser} from "@/api/auth/authDept";
import {filterSubAll} from "@/api/system/invSubWarehouse";

export default {
  data() {
    return {
      defaultSort: {prop: 'createTime', order: 'desc'},
      showSearch: true,
      filterQuery: {
        billAction: null,
        billNo: "",
        originType: null,
        thirdSysFk: "",
        page: 1,
        limit: 10,
        corpName: null,
        type: 1,
        editStatus: 1,
        emergency: '',
        deptCode: '',
        invCode: this.$store.getters.locInvCode,
      },
      formName: null,
      formMap: {
        add: "新增申购单据",
        update: "申购单据详情",
      },
      statusMap: {
        1: "草稿",
        2: "未审核",
        3: "已审核",
        4: "已拒绝"
      },
      emergencyMap: {
        1: "正常",
        2: "较急",
        3: "特急",
      },
      idQuery: {},
      editType: 2,
      total: 0,
      thirdSys: [],
      invCodebe: null,
      thirdSysDetail: null,
      busTypes: [],
      originTypes: [],
      invList: [],
      targetInvList: [],
      deptList: [],
      list: [],
      detailList: [],
      loading: false,
      actDateRange: [],
      actAuditDateRange: [],
      newSpDistributionVisible: false,
      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]);
            },
          },
        ],
      },

      pickerAuditOptions: {
        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: {
    onReset() {
      this.$router.push({
        path: "",
      });
      let targetDeptCode = this.filterQuery.targetDeptCode
      this.filterQuery = {
        billNo: "",
        thirdSysFk: "",
        billFlag: null,
        billAction: null,
        startDate: null,
        endDate: null,
        page: 1,
        limit: 10,
        corpName: null,
        type: 1,
        editStatus: 1,
        invCode: this.$store.getters.locInvCode,
        targetDeptCode: this.invCodebe,
      };
      if (targetDeptCode != this.invCodebe) {
        this.getInvList()
      }
      this.actDateRange = [];
      this.actAuditDateRange = [];
      this.getList();
    },

    onSubmitFind() {
      this.filterQuery.page = 1;
      this.getList();
    },
    hideSearch() {
      this.showSearch = !this.showSearch;
    },

    handleSortChange(column, prop, order) {
      if (column.order === 'descending') {
        this.filterQuery.sort = 'desc'
      } else {
        this.filterQuery.sort = 'asc'
      }
      this.filterQuery.orderBy = column.prop;
      this.getList();
    },

    getList() {
      if (this.actDateRange != null) {
        this.filterQuery.startDate = this.actDateRange[0];
        this.filterQuery.endDate = this.actDateRange[1];
      } else {
        this.filterQuery.startDate = null;
        this.filterQuery.endDate = null;
      }
      if (this.actAuditDateRange != null) {
        this.filterQuery.startAuditDate = this.actAuditDateRange[0];
        this.filterQuery.endAuditDate = this.actAuditDateRange[1];
      } else {
        this.filterQuery.startAuditDate = null;
        this.filterQuery.endAuditDate = null;
      }
      this.loading = true;
      this.filterQuery.status = 3;
      this.filterQuery.isUser = true
      listApply(this.filterQuery)
        .then((response) => {
          if (response.code == 20000) {
            this.list = response.data.list || [];
            this.total = response.data.total || 0;
            this.detailList = []
          } else {
            this.$message.error(response.message);
          }
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
          this.list = [];
          this.total = 0;
        });
    },
    handleDetail(row) {
      let query = {orderIdFk: row.id};
      this.loading = true;
      listApplyDetail(query) //查找该单号下的所有条码
        .then((response) => {
          this.detailList = response.data.list || [];
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
          this.detailList = [];
          this.total = 0;
        });
    },
    submitOrder(row) {
      this.loading = true;
      let tQuery = {
        editStatus: 2,
        purApplyEntity: row,
      }
      auditOrder(tQuery)
        .then(response => {
          this.loading = false;
          if (response.code === 20000) {
            this.$message.success("提交成功！");
            this.getList();
          } else {
            this.$message.error(response.message);
          }
        })
        .catch(() => {
          this.loading = false;
        })
    },
    deleteDialog(row) {
      this.$confirm("此操作将永久删除该单据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delApply(row.id)
            .then((response) => {
              this.loading = false;
              if (response.code == 20000) {
                this.$message.success("删除成功");
                this.getList();
              } else {
                this.$message.error(response.message);
              }
            })
            .catch(() => {
              this.loading = false;
            });

        })
        .catch(() => {
        });
    },
    handleCurrentChange(val) {
      this.filterQuery.page = val.page;
      this.getList();
    },

    closeDialog() {
      this.newSpDistributionVisible = false;
      this.getList();
      this.detailList = [];
    },
    getCurInvList() {
      getInvListByUser()
        .then((response) => {
          this.invList = response.data || [];
        })
        .catch(() => {
        });
    },

    newDistributionForm(index, row) {
      this.idQuery.id = '';
      if (this.$isNotBlank(row) && this.$isNotBlank(row.id)) {
        this.idQuery.id = row.id;
        this.idQuery.formData = row;
        this.formName = "update";
      } else
        this.formName = "add";
      this.newSpDistributionVisible = true;
    },
    getInvList() {
      var query = {
        parentId: this.filterQuery.targetDeptCode
      }
      filterSubAll(query).then((res) => {
        this.targetInvList = res.data || [];
      })
    },
    getDeptList() {
      let query = {
        spUse: true,
      };
      filterDepts(query).then((res) => {
        this.deptList = res.data || [];
        if (this.deptList.length > 0) {
          this.filterQuery.targetDeptCode = this.deptList[0].code
          this.invCodebe = this.filterQuery.targetDeptCode
        }
        this.getList();
        this.getInvList();
      });
    },
    printOrder(row) {
      printOrder(row)
        .then((response) => {
          const binaryData = [];
          binaryData.push(response);
          //获取blob链接。
          let url = window.URL.createObjectURL(
            new Blob(binaryData, {type: "application/pdf"})
          );
          this.loading = false;
          window.open(url);//打开新标签页，预览pdf。
          this.getList();
        })
        .catch(() => {
        });
    },

  }
  ,
  components: {
    pureApplyDetail,
  }
  ,
  filters: {
    statusFilterType(status) {
      const statusMap = {
        2: "warning",
        3: "success",
        4: "danger",
      };
      return statusMap[status];
    }
    ,
  }
  ,
  mounted() {
  }
  ,
  created() {
    this.getDeptList();
    this.getCurInvList();
  }
  ,
}
;
</script>
<style scoped>
.itemTag {
  float: left;
  text-align: left;
  margin-top: 10px;
  width: 25%;
}

.text {
  font-size: 13px;
  font-family: "Microsoft YaHei";
}

.el-row {
  display: flex;
  flex-wrap: wrap;
}

.el-col {
  border-radius: 4px;
  flex-wrap: wrap;
}
</style>

