<template>
  <div>
    <Card style="width:100%" :bordered="false" :dis-hover="true" v-show="!printShow && !addShow">
      <p slot="title">申购计划列表</p>
      <div slot="extra">
        <Button @click="addShow = true">新增申购计划</Button>
        <Button @click="exportData">导出明细</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">
          <Select clearable v-model="searchForm.jhlx" placeholder="计划类型">
            <Option v-for="item in jhlxList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </Col>
        <Col span="4">
          <DatePicker
            format="yyyy年MM月"
            :value="searchForm.jhyf"
            @on-change="searchForm.jhyf=$event"
            type="month"
            placeholder="计划月份"
          ></DatePicker>
        </Col>
        <Col span="4">
          <DatePicker
            :value="searchForm.zdrq"
            @on-change="searchForm.zdrq=$event"
            format="yyyy/MM/dd HH:mm"
            type="datetimerange"
            placeholder="制单日期"
          ></DatePicker>
        </Col>
        <Col span="4">
          <Select clearable filterable v-model="searchForm.fgcgy" placeholder="分管采购员">
            <Option
              v-for="item in fgcgyList"
              :value="item.userId"
              :key="item.userId"
            >{{ item.userName }}</Option>
          </Select>
        </Col>
      </Row>
      <Row :gutter="10" style="margin-bottom: 10px">
        <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">
          <Input v-model="searchForm.title" placeholder="申请人/物料名称/计划单据号/标题" />
        </Col>
        <Col span="4">
          <Button type="primary" style="width: 80px" @click="getTableData">查询</Button>
        </Col>
      </Row>
      <!-- <Row style="margin-bottom: 10px; text-align: right">
        <Button type="primary" style="width: 80px" @click="getTableData">查询</Button>
      </Row>-->
      <Table
        :columns="tableColumn"
        style="width: 100%"
        :data="tableData"
        :height="resizeHeight - 65"
        :loading="tableLoading"
        @on-select="tableOnSelect"
        @on-row-dblclick="goDetail"
      >
        <template slot-scope="{ row, index }" slot="status">
          <div>
            <span v-if="row.status == '0'">未申购</span>
            <span v-if="row.status == '1'">待采购</span>
            <span v-if="row.status == '2'">采购中</span>
            <span v-if="row.status == '3'">已取消</span>
            <span v-if="row.status == '4'">已采购</span>
            <span v-if="row.status == '5'">审核不通过</span>
          </div>
        </template>
        <template slot-scope="{ row, index }" slot="applyStatus">
          <div>
            <span v-if="row.applyStatus == '0'">未发起</span>
            <span v-if="row.applyStatus == '1'">审批中</span>
            <span v-if="row.applyStatus == '2'">审批通过</span>
            <span v-if="row.applyStatus == '3'">审批不通过</span>
            <!-- <span v-if="row.applyStatus == '4'">审批驳回</span> -->
          </div>
        </template>
        <template slot-scope="{ row, index }" slot="type">
          <div>
            <span v-if="row.type == '1'">计划性申购</span>
            <span v-if="row.type == '2'">临时申购</span>
          </div>
        </template>
        <template slot-scope="{ row, index }" slot="action">
          <div>
            <a href="javascript:;" @click="editRow(row)">编辑</a>
            <!-- <a href="javascript:;">复制</a> -->
            <a href="javascript:;" v-if="row.applyStatus == '0'" @click="deleteRow(row)">删除</a>
            <a
              href="javascript:;"
              v-if="row.applyStatus == '2' || row.applyStatus == '3'"
              @click="copyRow(row)"
            >复制</a>
            <a href="javascript:;" @click="printRow(row)">打印</a>
            <a
              href="javascript:;"
              v-if="row.applyStatus == '0' || row.applyStatus == '3'"
              @click="submitRow(row)"
            >提交</a>
          </div>
        </template>
      </Table>
      <Page align="right" :total="pageTotal" @on-change="pageChange" show-total />
    </Card>
    <planAdd
      ref="add"
      @return="() => {addShow = false; getTableData()}"
      :ssqyList="ssqyList"
      :cgyList="fgcgyList"
      v-show="addShow"
    />
    <planPrint ref="print" @return="() => {printShow = false ; getTableData()}" v-show="printShow" />
  </div>
</template>

<script>
import {
  queryPurchaseApplyList,
  getAreaList,
  getProjectList,
  deletePurchaseApply,
  getJobList,
  exportPurchaseInfo,
  submitPurchaseApply,
  queryPurchaseApplyInfo,
  addPurchaseApply
} from "@/service/getData";
import planAdd from "./components/plan/planAdd";
import PlanPrint from "./components/plan/planPrint";
export default {
  components: {
    planAdd,
    PlanPrint
  },
  data() {
    return {
      addShow: false,
      printShow: false,
      //  自适应尺寸↓
      resizeHeight: 100,
      resizeWidth: 100,
      handleWidth: 100,
      //   顶部搜索
      searchForm: {
        ssqy: "", //所属区域
        glxm: "", //关联项目
        jhlx: "", //计划类型
        jhyf: "", //计划月份
        zdrq: [], //制单日期
        fgcgy: "", //分管采购员
        spzt: "", //审批状态
        title: "" //申请人/物料名称/计划单据号/标题
      },
      ssqyList: [],
      glxmList: [],
      jhlxList: [
        { label: "计划性申购", value: 1 },
        { label: "临时申购", value: 2 }
      ],
      fgcgyList: [],
      spztList: [
        { label: "未发起", value: 0 },
        { label: "审批中", value: 1 },
        { label: "审批通过", value: 2 },
        { label: "审批不通过", value: 3 }
        // { label: "审批驳回", value: 4 }
      ],
      // 表格参数
      tableLoading: false,
      pageTotal: 0,
      pageNum: 1,
      tableColumn: [
        // {
        //   type: "selection",
        //   width: 60,
        //   align: "center"
        // },
        {
          title: "操作",
          slot: "action",
          width: 180
        },
        {
          title: "计划单据号",
          key: "code",
          tooltip: "true",
          width: 100
        },
        {
          title: "标题",
          key: "title",
          tooltip: "true",
          width: 100
        },
        {
          title: "状态",
          slot: "status",
          tooltip: "true",
          width: 100
        },
        {
          title: "审批状态",
          slot: "applyStatus",
          tooltip: "true",
          width: 100
        },
        {
          title: "计划类型",
          slot: "type",
          tooltip: "true",
          width: 100
        },
        {
          title: "计划月份",
          key: "applyMonth",
          tooltip: "true",
          width: 100
        },
        {
          title: "计划到货时间",
          key: "arriveTime",
          tooltip: "true",
          width: 100
        },
        {
          title: "总价（元）",
          key: "referencePrice",
          tooltip: "true",
          width: 100
        },
        {
          title: "申请人",
          key: "applicantName",
          tooltip: "true",
          width: 100
        },
        {
          title: "分管采购员",
          key: "purchaserName",
          tooltip: "true",
          width: 100
        },
        {
          title: "所属区域",
          key: "areaName",
          tooltip: "true",
          width: 100
        },
        {
          title: "关联项目",
          key: "projectName",
          tooltip: "true",
          width: 100
        },
        {
          title: "创建时间",
          key: "createTime",
          tooltip: "true",
          width: 100
        },
        {
          title: "提交时间",
          key: "submitTime",
          tooltip: "true",
          width: 100
        },
        {
          title: "审批通过时间",
          key: "applyTime",
          tooltip: "true",
          width: 100
        }
      ],
      tableData: [],
      tableSelect: []
    };
  },
  created() {
    this.getTableData();
    getAreaList(localStorage.user_id).then(res => {
      this.ssqyList = res.items;
    });
    getJobList().then(res => {
      if (res.status == 200) {
        this.fgcgyList = res.data;
      } else {
        this.$Message.error("获取分管采购员列表失败！");
      }
    });
  },
  methods: {
    goDetail(row, index) {
      if (row.applyStatus != "3") {
        this.editRow(row);
      } else {
        window.open(
          `https://test.hajwy.com/purchase-web/#/viewPurchaseApply?id=${row.id}`
        );
      }
      // window.open(`/#/viewPurchaseApply?id=${row.id}`);
    },
    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) {},
    //申购计划导出
    exportData() {
      let postData = {
        type: this.searchForm.jhlx,
        applyMonth: this.searchForm.jhyf,
        purchaserId: this.searchForm.fgcgy,
        applyStatus: this.searchForm.spzt,
        page: this.pageNum,
        pageSize: 10,
        queryText: this.searchForm.title,
        // createStartTime: this.searchForm.zdrq[0],
        // createEndTime: this.searchForm.zdrq[1],
        areaIds: this.searchForm.ssqy,
        projectIds: this.searchForm.glxm
      };
      if (this.searchForm.zdrq.length > 0) {
        postData.createStartTime = this.searchForm.zdrq[0];
        postData.createEndTime = this.searchForm.zdrq[1];
      }
      console.log(postData, 11111111111111111);
      exportPurchaseInfo(postData);
    },
    //打印
    printRow(row) {
      this.printShow = true;
      this.$refs.print.getPrintData(row.id);
    },
    //列表页方法
    getTableData() {
      let postData = {
        type: this.searchForm.jhlx,
        applyMonth: this.searchForm.jhyf,
        purchaserId: this.searchForm.fgcgy,
        applyStatus: this.searchForm.spzt,
        page: this.pageNum,
        pageSize: 10,
        queryText: this.searchForm.title,
        areaIds: this.searchForm.ssqy,
        projectIds: this.searchForm.glxm
      };
      if (this.searchForm.zdrq.length > 0) {
        postData.createStartTime = this.searchForm.zdrq[0];
        postData.createEndTime = this.searchForm.zdrq[1];
      }
      this.tableLoading = true;
      queryPurchaseApplyList(postData).then(res => {
        this.tableLoading = false;
        if (res.status == 200) {
          this.tableData = res.data.records;
          for (let i in this.tableData) {
            if (this.tableData[i].arriveTime) {
              this.tableData[i].arriveTime = this.tableData[i].arriveTime.split(
                " "
              )[0];
            }
          }
          this.pageTotal = res.data.total;
        } else {
          this.$Message.error(res.message);
        }
      });
    },
    //行编辑
    editRow(row) {
      if (row.applyStatus != "3") {
        this.addShow = true;
        this.$refs.add.planType = "edit";
        this.$refs.add.getSgjh(row.id);
      } else {
        window.open(
          `https://test.hajwy.com/purchase-web/#/viewPurchaseApply?id=${row.id}`
        );
      }
    },
    //行删除
    deleteRow(row) {
      this.$Modal.confirm({
        title: "删除",
        content: "是否确定删除该申购计划？",
        okText: "确定",
        onOk: () => {
          let postData = {
            id: row.id
          };
          deletePurchaseApply(postData).then(res => {
            if (res.status == 200) {
              this.$Message.success("删除成功！");
              this.getTableData();
            } else {
              this.$Message.error(res.message);
            }
          });
        }
      });
    },
    //行复制
    copyRow(row) {
      let postData = {
        id: row.id
      };
      queryPurchaseApplyInfo(postData).then(res => {
        if (res.status == 200) {
          let data = res.data;
          let postData = {
            areaId: data.areaId,
            areaName: data.areaName,
            projectId: data.projectId,
            projectName: data.projectName,
            type: data.type,
            applyMonth: `${new Date().getFullYear()}年${new Date().getMonth() +
              1}月`,
            purchaserId: data.purchaserId,
            purchaserName: data.purchaserName,
            applicantId: localStorage.user_id,
            applicantName: localStorage.user_name,
            attachmentList: data.filesList,
            remark: data.remark
          };
          let arr = [];
          for (let i in data.detailList) {
            data.detailList[i].arriveTime = "";
          }
          arr = data.detailList;
          addPurchaseApply(postData).then(res => {
            if (res.status == 200) {
              this.$Message.success("复制申购计划成功!");
              this.addShow = true;
              this.$refs.add.planType = "edit";
              this.$refs.add.getSgjh(res.data.id, arr);
            }
          });
        } else {
          this.$Message.error(res.message);
        }
      });
    },
    //行提交
    submitRow(row) {
      this.$Modal.confirm({
        title: "提交",
        content: "是否确定提交该申购计划？",
        okText: "确定",
        onOk: () => {
          let postData = {
            id: row.id
          };
          submitPurchaseApply(postData).then(res => {
            if (res.status == 200) {
              this.$Message.success("提交成功！");
              this.getTableData();
            } else {
              this.$Message.error(res.message);
            }
          });
        }
      });
    },
    pageChange(val) {
      this.pageNum = val;
      this.getTableData();
    },
    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>
