<template>
  <div>
    <Card style="width:100%" :bordered="false" :dis-hover="true" v-show="!addShow && !printShow">
      <p slot="title">采购订单列表</p>
      <div slot="extra">
        <Button @click="addOrderShow" v-if="buttonShow.add">新增采购订单</Button>
        <Button @click="exportData" v-if="buttonShow.export">导出明细</Button>
        <!-- <Button @click="printShow = true">打印---测试</Button> -->
      </div>
      <Row :gutter="10" style="margin-bottom: 10px">
        <Col span="4">
          <Select clearable v-model="searchForm.ssqy" placeholder="所属区域" @on-change="ssqyChange">
            <Option
              v-for="item in ssqyList"
              :value="item.areaId"
              :key="item.areaId"
            >{{ item.areaName }}</Option>
          </Select>
        </Col>
        <Col span="4">
          <Select clearable v-model="searchForm.glxm" placeholder="关联项目" @on-change="glxmChange">
            <Option
              v-for="item in glxmList"
              :value="item.projectId"
              :key="item.projectId"
            >{{ item.projectName }}</Option>
          </Select>
        </Col>
        <Col span="4">
          <Input v-model="searchForm.cgr" placeholder="采购人" />
        </Col>
        <Col span="4">
          <DatePicker
            format="yyyy-MM-dd HH:mm:ss"
            :value="searchForm.xdsj"
            @on-change="dateChange"
            type="datetimerange"
            placeholder="下单时间"
          ></DatePicker>
        </Col>
        <Col span="4">
          <DatePicker
            format="yyyy-MM-dd HH:mm:ss"
            :value="searchForm.jhsj"
            @on-change="dateChange1"
            type="daterange"
            placeholder="交货时间"
          ></DatePicker>
        </Col>
      </Row>
      <Row :gutter="10" style="margin-bottom: 10px">
        <Col span="4">
          <Input v-model="searchForm.shr" placeholder="收货人" />
        </Col>
        <Col span="4">
          <Select clearable v-model="searchForm.gys" filterable placeholder="供应商">
            <Option v-for="item in gysList" :value="item.gpId" :key="item.gpId">{{ item.gpName }}</Option>
          </Select>
        </Col>
        <Col span="4">
          <Select clearable v-model="searchForm.spzt" placeholder="审批状态">
            <Option v-for="item in spztList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </Col>
        <Col span="4">
          <Select clearable v-model="searchForm.ddzt" placeholder="订单状态">
            <Option v-for="item in ddztList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </Col>
        <Col span="4">
          <Input v-model="searchForm.title" placeholder="订购编号/标题/申购单号/物料名称" />
        </Col>
        <Col span="4">
          <Button type="primary" style="width: 80px" @click="pageNum = 1 ;getTableData()">查询</Button>
        </Col>
      </Row>
      <Table
        style="width:100%"
        :columns="tableColumn"
        :data="tableData"
        :height="resizeHeight - 65"
        :loading="tableLoading"
        @on-select="tableOnSelect"
        @on-row-dblclick="goDetail"
      >
        <template slot-scope="{ row, index }" slot="approvalState">
          <div>
            <span v-if="row.approvalState == '1'">未提交</span>
            <span v-if="row.approvalState == '2'">审核中</span>
            <span v-if="row.approvalState == '3'">审核通过</span>
            <span v-if="row.approvalState == '4'">审核拒绝</span>
          </div>
        </template>
        <template slot-scope="{ row, index }" slot="orderState">
          <div>
            <span v-if="row.orderState == '1'">未下单</span>
            <span v-if="row.orderState == '2'">待下单</span>
            <span v-if="row.orderState == '3'">已下单</span>
            <span v-if="row.orderState == '4'">入库中</span>
            <span v-if="row.orderState == '5'">已入库</span>
            <span v-if="row.orderState == '6'">已取消</span>
          </div>
        </template>
        <template slot-scope="{ row, index }" slot="action">
          <div>
            <a href="javascript:;" v-if="buttonShow.check" @click="checkRow(row)">{{ '查看' }}</a>
            <a
              href="javascript:;"
              @click="editRow(row)"
              v-if="buttonShow.edit && row.creator == userId"
            >{{ '编辑' }}</a>
            <a
              href="javascript:;"
              v-if="buttonShow.submit && row.approvalState == '1' && row.creator == userId"
              @click="submitRow(row.orderId)"
            >提交</a>
            <a
              href="javascript:;"
              v-if="buttonShow.delete && row.approvalState == '1' && row.creator == userId"
              @click="deleteRow(row)"
            >删除</a>
            <a
              href="javascript:;"
              v-if="buttonShow.print && row.orderState != '6'"
              @click="printRow(row)"
            >打印</a>
            <a
              href="javascript:;"
              @click="cgddxd(row.orderId)"
              v-if="buttonShow.order && row.orderState == '2'"
            >下单</a>
            <!-- <a href="javascript:;" @click="cgddqx(row.orderId)" v-if="row.orderState == '2'">取消订单</a> -->
          </div>
        </template>
      </Table>
      <Page align="right" :current="pageNum" :total="pageTotal" @on-change="pageChange" show-total />
    </Card>
    <orderAdd
      ref="add"
      :glqyList="ssqyList"
      @return="() => {addShow = false; getTableData()}"
      v-show="addShow"
    />
    <orderPrint ref="print" @return="() => {printShow = false; getTableData()}" v-show="printShow" />
  </div>
</template>

<script>
import {
  getPurchaseOrder,
  deletePurchaseOrder,
  findPurchaseOrder,
  selectGoodProviderSelectionList,
  exportPurchaseOrder,
  getAreaList,
  getProjectList,
  editPurchaseOrderState,
  submitPurchaseOrder,
  getUserButtons,
} from "@/service/getData";
import orderAdd from "./components/order/orderAdd";
import orderPrint from "./components/order/orderPrint";
export default {
  name: "purchaseOrder",
  components: {
    orderAdd,
    orderPrint,
  },
  data() {
    return {
      addShow: false,
      printShow: false,
      userId: localStorage.user_id,
      //  自适应尺寸↓
      resizeHeight: 100,
      resizeWidth: 100,
      handleWidth: 100,
      buttonShow: {
        check: false,
        add: false,
        submit: false,
        export: false,
        order: false,
        edit: false,
        delete: false,
        print: false,
      },
      //   查询参数
      searchForm: {
        ssqy: "", //所属区域
        glxm: "", //关联项目
        glcgjh: "", //关联采购计划
        cgr: "", //采购人
        xdsj: [], //下单时间
        jhsj: [], //交货时间
        shr: "", //收货人
        gys: "", //供应商
        spzt: "", //审批状态
        ddzt: "", //订单状态
        title: "", //订单编号或标题
      },
      ssqyList: [],
      glxmList: [],
      glcgjhList: [],
      cgrList: [],
      shrList: [],
      gysList: [],
      spztList: [
        { value: 1, label: "未提交" },
        { value: 2, label: "审核中" },
        { value: 3, label: "审核通过" },
        { value: 4, label: "审核拒绝" },
      ],
      ddztList: [
        { value: 1, label: "未下单" },
        { value: 2, label: "待下单" },
        { value: 3, label: "已下单" },
        { value: 4, label: "入库中" },
        { value: 5, label: "已入库" },
        { value: 6, label: "已取消" },
      ],
      //   表格参数
      tableLoading: false,
      pageTotal: 0,
      pageNum: 1,
      tableColumn: [
        // {
        //   type: "selection",
        //   width: 60,
        //   align: "center"
        // },
        {
          title: "操作",
          slot: "action",
          width: 180,
        },
        {
          title: "订购编号",
          key: "orderCode",
          tooltip: true,
          width: 200,
        },
        {
          title: "标题",
          key: "title",
          tooltip: true,
          width: 250,
        },
        {
          title: "审批状态",
          slot: "approvalState",
          tooltip: true,
          width: 100,
        },
        {
          title: "状态",
          slot: "orderState",
          tooltip: true,
          width: 100,
        },
        {
          title: "总价（元）",
          key: "totalPrice",
          tooltip: true,
          width: 100,
        },
        {
          title: "申请人",
          key: "applicantName",
          tooltip: true,
          width: 200,
        },
        {
          title: "分管采购员",
          key: "purchaserName",
          tooltip: true,
          width: 200,
        },
        {
          title: "申请时间",
          key: "applicantTime",
          tooltip: true,
          width: 180,
        },
        {
          title: "所属区域",
          key: "areaName",
          tooltip: true,
          width: 100,
        },
        {
          title: "关联项目",
          key: "projectName",
          tooltip: true,
          width: 100,
        },
      ],
      tableData: [],
    };
  },
  created() {
    this.getTableData();
    this.getUserAuth();
    getAreaList(localStorage.user_id).then((res) => {
      this.ssqyList = res.items;
    });
    selectGoodProviderSelectionList().then((res) => {
      this.gysList = res.data;
    });
  },
  methods: {
    dateChange(val, value) {
      if (value == "date") {
        this.searchForm.xdsj = [val[0], val[1].replace("00:00:00", "23:59:59")];
      } else {
        this.searchForm.xdsj = val;
      }
    },
    dateChange1(val, value) {
      if (value == "date") {
        this.searchForm.jhsj = [val[0], val[1].replace("00:00:00", "23:59:59")];
      } else {
        this.searchForm.jhsj = val;
      }
    },
    //获取按钮权限
    getUserAuth() {
      //获取用户在当前页面的权限
      var self = this;
      let menuId = sessionStorage.getItem("refresh_child_id");
      let userForm = {
        userId: localStorage.user_id,
        menuId: menuId,
      };
      let buttons = [
        "check",
        "add",
        "submit",
        "export",
        "order",
        "edit",
        "delete",
        "print",
      ];
      getUserButtons(userForm).then((result) => {
        if (result.resultCode == "200") {
          result.data.forEach((item) => {
            //  item.code
            if (buttons.includes(item.code)) {
              self.buttonShow[item.code] = true;
            }
          });
        }
      });
    },
    goDetail(row) {
      // if (this.buttonShow.edit) {
      //   this.editRow(row);
      // }
      let routeUrl = this.$router.resolve({
        path: "/viewPurchaseOrder",
        query: {
          id: row.orderId,
        },
      });
      window.open(routeUrl.href, "_blank");
      // window.open(
      //   `https://test.hajwy.com/purchase-web/#/viewPurchaseOrder?id=${row.orderId}`
      // );
      // window.open(`/#/viewPurchaseOrder?id=${row.orderId}`)
    },
    resizePage() {
      this.resizeHeight = window.innerHeight - 282;
      this.resizeWidth = window.innerWidth;
      // this.handleWidth = this.$refs.handleHolder.offsetWidth;
    },
    ssqyChange(val) {
      let postData = {
        areaId: this.searchForm.ssqy,
        userId: localStorage.user_id,
      };
      getProjectList(postData).then((res) => {
        this.searchForm.glxm = "";
        this.glxmList = res.items;
      });
    },
    glxmChange(val) {},
    pageChange(val) {
      this.pageNum = val;
      this.getTableData();
    },
    exportData() {
      let allArea = [];
      let allProject = [];
      let areaList = JSON.parse(localStorage.getItem("areaList"));
      let projectList = JSON.parse(localStorage.getItem("projectList"));
      areaList.forEach((a) => allArea.push(a.areaId));
      projectList.forEach((a) => allProject.push(a.projectId));
      let postData = {
        areaIds: `${this.searchForm.ssqy}`,
        projectIds: `${this.searchForm.glxm}`,
        purchaserName: this.searchForm.cgr,
        startTime: this.searchForm.xdsj[0],
        endTime: this.searchForm.xdsj[1],
        deliveryStartTime: this.searchForm.jhsj[0],
        deliveryEndTime: this.searchForm.jhsj[1],
        receivedName: this.searchForm.shr,
        gpId: this.searchForm.gys,
        approvalState: this.searchForm.spzt,
        orderState: this.searchForm.ddzt,
        queryText: this.searchForm.title,
      };
      if (!this.searchForm.ssqy) {
        postData.areaIds = allArea.join(",");
      }
      if (!this.searchForm.glxm) {
        postData.projectIds = allProject.join(",");
      }
      exportPurchaseOrder(postData);
    },
    //列表方法
    getTableData() {
      let allArea = [];
      let allProject = [];
      let areaList = JSON.parse(localStorage.getItem("areaList"));
      let projectList = JSON.parse(localStorage.getItem("projectList"));
      areaList.forEach((a) => allArea.push(a.areaId));
      projectList.forEach((a) => allProject.push(a.projectId));
      let postData = {
        page: this.pageNum,
        pageSize: 10,
        areaIds: `${this.searchForm.ssqy}`,
        projectIds: `${this.searchForm.glxm}`,
        purchaserName: this.searchForm.cgr,
        startTime: this.searchForm.xdsj[0],
        endTime: this.searchForm.xdsj[1],
        deliveryStartTime: this.searchForm.jhsj[0],
        deliveryEndTime: this.searchForm.jhsj[1],
        receivedName: this.searchForm.shr,
        gpId: this.searchForm.gys,
        approvalState: this.searchForm.spzt,
        orderState: this.searchForm.ddzt,
        queryText: this.searchForm.title,
      };
      if (!this.searchForm.ssqy) {
        postData.areaIds = allArea.join(",");
      }
      if (!this.searchForm.glxm) {
        postData.projectIds = allProject.join(",");
      }
      this.tableLoading = true;
      getPurchaseOrder(postData).then((res) => {
        this.tableLoading = false;
        if (res.status == 200) {
          this.tableData = res.data.records;
          this.pageTotal = res.data.total;
        } else {
          this.$Message.error("获取采购订单列表失败。");
        }
      });
    },
    addOrderShow() {
      this.addShow = true;
      let date = new Date();
      let year = date.getFullYear();
      let month =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1;
      let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      let minute =
        date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      let second =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      let dateArr = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
      this.$refs.add.form.xdrq = dateArr;
    },
    checkRow(row) {
      let routeUrl = this.$router.resolve({
        path: "/viewPurchaseOrder",
        query: {
          id: row.orderId,
        },
      });
      window.open(routeUrl.href, "_blank");
    },
    editRow(row) {
      this.addShow = true;
      this.$refs.add.getCgddXq(row.orderId);
    },
    submitRow(id) {
      this.$Modal.confirm({
        title: "提交",
        content: "是否确定提交该采购订单？",
        okText: "确定",
        onOk: () => {
          let postData = {
            orderId: id,
          };
          submitPurchaseOrder(postData).then((res) => {
            if (res.status == 200) {
              this.$Message.success("提交成功！");
              this.getTableData();
            } else {
              this.$Message.error(res.message);
            }
          });
        },
      });
    },
    cgddxd(id) {
      this.$Modal.confirm({
        title: "下单",
        content: "是否确定下单？",
        okText: "确定",
        onOk: () => {
          let str = `?orderId=${id}&state=3`;
          editPurchaseOrderState(str).then((res) => {
            if ((res.status = 200)) {
              this.$Message.success("下单成功！");
              this.getTableData();
            }
          });
        },
      });
    },
    cgddqx(id) {
      this.$Modal.confirm({
        title: "取消订单",
        content: "是否确定取消该订单？",
        okText: "确定",
        onOk: () => {
          let str = `?orderId=${id}&state=6`;
          editPurchaseOrderState(str).then((res) => {
            if ((res.status = 200)) {
              this.$Message.success("取消订单成功！");
              this.getTableData();
            }
          });
        },
      });
    },
    deleteRow(row) {
      this.$Modal.confirm({
        title: "删除",
        content: "是否确定删除该采购订单？",
        okText: "确定",
        onOk: () => {
          deletePurchaseOrder(row.orderId).then((res) => {
            if ((res.status = 200)) {
              this.$Message.success("删除成功！");
              this.getTableData();
            }
          });
        },
      });
    },
    printRow(row) {
      this.printShow = true;
      this.$refs.print.getData(row.orderId);
    },
    tableOnSelect(selection, row) {},
  },
  mounted: function () {
    //  监听浏览器页面尺寸
    window.addEventListener("resize", this.resizePage);
    this.resizePage();
  },
};
</script>

<style lang="scss" scoped>
ivu-card-head-inner,
.ivu-card-head p {
  display: inline-block;
  width: 100%;
  height: 20px;
  line-height: 20px;
  font-size: 14px;
  color: #17233d;
  font-weight: 700;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-weight: normal;
}
</style>
