<template>
  <div class="instock_order">
    <Toptitle title="领料出库单">
      <slot name="titleButton">
        <!-- <Button @click="handleCodeRule"
                type="primary"
                ghost
                style="margin-right:10px;">编码规则</Button> -->
        <!-- <Button type="primary"
                @click="handleGoPage(1,'')"
                style="margin-right:10px;">新增</Button> -->
      </slot>
    </Toptitle>
    <div class="instock_order_content">
      <div class="instock_order_search">
        <Form :label-width="110" :model="searchData">
          <FormItem label="领料出库单号:">
            <Input
              type="text"
              size="small"
              v-model="searchData.order_out_no"
              clearable
              style="width: 150px"
              placeholder="请输入领料出库单号"
            />
          </FormItem>
          <FormItem label="项目名称:">
            <Tooltip :content="supplierTitle" placement="top" transfer>
              <Select
                size="small"
                v-model="searchData.project_title"
                style="width: 150px"
                placeholder="请选择"
                filterable
                clearable
                @on-change="supplyChange"
              >
                <Option
                  v-for="(item, index) in suppliersList"
                  :key="index"
                  :value="item"
                  :label="item"
                />
              </Select>
            </Tooltip>
          </FormItem>
          <FormItem label="仓库:">
            <Select
              v-model="searchData.warehouse_id"
              size="small"
              clearable
              style="width: 150px"
            >
              <Option
                v-for="sitem in warehouseList"
                :key="sitem.id"
                :label="sitem.title"
                :value="sitem.id"
              >
              </Option>
            </Select>
          </FormItem>
          <FormItem label="出库类型:">
            <Select v-model="searchData.type" filterable clearable size="small">
              <Option
                v-for="sitem in purchaseTypeList"
                :key="sitem.id"
                :label="sitem.title"
                :value="sitem.id"
              >
              </Option>
            </Select>
          </FormItem>
          <FormItem label="制单人:">
            <Select
              v-model="searchData.crt_id"
              size="small"
              filterable
              clearable
              style="width: 150px"
            >
              <Option
                v-for="sitem in userList"
                :key="sitem.id"
                :label="sitem.nickname"
                :value="sitem.id"
              >
              </Option>
            </Select>
          </FormItem>
          <FormItem label="审批状态:">
            <Select
              v-model="searchData.state"
              size="small"
              clearable
              style="width: 150px"
            >
              <Option label="未审批" :value="0" />
              <Option label="已审批" :value="1" />
            </Select>
          </FormItem>
          <FormItem label="审批人:">
            <Select
              v-model="searchData.check_id"
              size="small"
              filterable
              clearable
              style="width: 150px"
            >
              <Option
                v-for="sitem in userList"
                :key="sitem.id"
                :label="sitem.nickname"
                :value="sitem.id"
              >
              </Option>
            </Select>
          </FormItem>
          <FormItem label="单据日期:" style="width: 430px">
            <DatePicker
              type="date"
              size="small"
              style="width: 150px"
              placeholder="年/月/日"
              v-model="searchData.start_time"
            ></DatePicker>
            ~
            <DatePicker
              type="date"
              size="small"
              style="width: 150px"
              placeholder="年/月/日"
              v-model="searchData.end_time"
            ></DatePicker>
          </FormItem>
          <FormItem label="订单创建时间:" style="width: 430px">
            <DatePicker
              type="date"
              size="small"
              style="width: 150px"
              placeholder="年/月/日"
              v-model="searchData.order_start_time"
            ></DatePicker>
            ~
            <DatePicker
              type="date"
              size="small"
              style="width: 150px"
              placeholder="年/月/日"
              v-model="searchData.order_end_time"
            ></DatePicker>
          </FormItem>
          <FormItem>
            <Button
              type="primary"
              size="small"
              @click="searchClick(searchData)"
              style="margin-right: 10px"
              >搜索</Button
            >
          </FormItem>
        </Form>
      </div>
      <div class="addBtn">
        <Button
          type="primary"
          @click="handleGoPage(1, '')"
          style="margin-right: 10px"
          size="small"
          >新增</Button
        >
      </div>

      <div class="instock_order_content_table">
        <Table
          :columns="tableColumns"
          border
          :max-height="500"
          :data="tableData"
        >
          <template slot="setSlot" slot-scope="{ row, index }">
            <!-- <a style="margin: 0 5px" @click="handleSet(6, row, index)">复制</a> -->
            <a style="margin: 0 5px" @click="handleSet(2, row, index)">详情</a>
            <a
              style="margin: 0 5px"
              v-show="row.state == 0"
              @click="handleSet(3, row, index)"
              >编辑</a
            >
            <a
              style="margin: 0 5px"
              v-show="row.state == 0"
              @click="handleSet(4, row, index)"
              >删除</a
            >
            <a style="margin: 0 5px" @click="handleSet(5, row, index)">{{
              row.state == 1 ? "弃审" : "审批"
            }}</a>
          </template>
        </Table>
      </div>
    </div>
    <div class="instock_order_content_page">
      <Page
        :page-size-opts="[10, 20, 30, 40, 100]"
        @on-page-size-change="changeSize"
        @on-change="changePage"
        :current="pageIndex"
        show-total
        :total="total"
        show-sizer
        :page-size="pageSize"
      />
    </div>
  </div>
</template>

<script>
import colorSettingVue from "../../BasicSettings/colorSetting.vue";
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

export default {
  name: "",
  components: {},
  props: {},
  // import引入的组件需要注入到对象中才能使用
  data() {
    // 这里存放数据
    return {
      supplierTitle: "",
      suppliersList: [],
      warehouseList: [],
      purchaseTypeList: [],
      searchData: {
        order_out_no: "",
        type: "",
        warehouse_id: "",
        crt_id: "",
        state: "",
        check_id: "",
        start_time: "",
        end_time: "",
        order_start_time: "",
        order_end_time: "",
      },
      tableColumns: [
        {
          title: "领料出库单号",
          key: "order_out_no",
          align: "center",
          minWidth: 140,
        },
        {
          title: "项目名称",
          key: "project_title",
          align: "center",
          minWidth: 140,
        },
        {
          title: "出库类型",
          key: "type",
          align: "center",
          minWidth: 120,
          render: (h, params) => {
            const { row } = params;
            return h("span", {}, row.type_title);
          },
        },
        {
          title: "仓库",
          key: "warehouse_title",
          align: "center",
          minWidth: 120,
        },
        { title: "制单人", key: "user_name", align: "center", minWidth: 100 },
        {
          title: "审批状态",
          key: "state",
          align: "center",
          minWidth: 140,
          render: (h, params) => {
            const { row } = params;
            const text = row.state == 0 ? "未审批" : "已审批";
            return h("span", {}, text);
          },
        },
        { title: "审批人", key: "check_name", align: "center", minWidth: 100 },
        {
          title: "单据日期",
          key: "order_time",
          align: "center",
          minWidth: 140,
          render: (h, params) => {
            const { row } = params;
            return h("span", {}, this.func.replaceDateNoHMS(row.order_time));
          },
        },
        {
          title: "订单创建时间",
          key: "crt_time",
          align: "center",
          minWidth: 140,
          render: (h, params) => {
            const { row } = params;
            return h("span", {}, this.func.replaceDate(row.crt_time));
          },
        },
        {
          title: "操作",
          key: "code",
          align: "center",
          minWidth: 200,
          slot: "setSlot",
        },
      ],
      tableData: [{}],
      pageIndex: localStorage.getItem("pageIndex") * 1 || 1,
      pageSize: 10,
      total: 0,
      userList: [],
      newSearchData:{}
    };
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    //获取出库类型
    this.axios({
      method: "get",
      url: "/api/basic_purchase_list",
      params: { type_id: 3 },
    })
      .then((res) => {
        this.purchaseTypeList = res.data.data;
      })
      .catch((err) => {});
    // 获取操作员
    this.axios("/api/user").then((res) => (this.userList = res.data.data));
    // 获取仓库列表
    this.axios({ method: "get", url: "/api/warehouse" })
      .then((res) => {
        this.warehouseList = res.data.filter((v) => {
          return v.type_id == 1;
        });
      })
      .catch((err) => {});
    // 获取供应商列表
    this.axios({ method: "get", url: "/api/purchase_orders_list" })
      .then((res) => {
        this.suppliersList = res.data.project_name;
      })
      .catch((err) => {});
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    if (localStorage.getItem("searchData")) {
      this.searchData = JSON.parse(localStorage.getItem("searchData"));
    }
    if (localStorage.getItem("newSearchData")) {
      this.newSearchData = JSON.parse(localStorage.getItem("newSearchData"));
    }
    this.initData(this.newSearchData);
  },
  methods: {
    searchClick(row) {
      localStorage.setItem("newSearchData", JSON.stringify(row));
      this.newSearchData = row;
      this.initData(row);
    },
    supplyChange(e) {
      this.supplierTitle = e;
    },
    initData(row) {
      if (row) {
        var obj = JSON.parse(JSON.stringify(this.searchData));
        typeof this.searchData.start_time == "object"
          ? (obj.start_time = Date.parse(obj.start_time)
              .toString()
              .slice(0, 10))
          : "";
        typeof this.searchData.end_time == "object"
          ? (obj.end_time = Date.parse(obj.end_time).toString().slice(0, 10))
          : "";
        typeof this.searchData.order_start_time == "object"
          ? (obj.order_start_time = Date.parse(obj.order_start_time)
              .toString()
              .slice(0, 10))
          : "";
        typeof this.searchData.order_end_time == "object"
          ? (obj.order_end_time = Date.parse(obj.order_end_time)
              .toString()
              .slice(0, 10))
          : "";
      } else {
        var obj = {};
      }
      this.axios({
        method: "get",
        url: "/api/warehouse_order_out_list",
        params: {
          ...obj,
          page_index: this.pageIndex,
          page_size: this.pageSize,
        },
      })
        .then((res) => {
          this.tableData = res.data.data;
          this.total = res.data.total;
          // console.log(res)
        })
        .catch((err) => {});
    },
    handleSet(type, row, index) {
      // 1新增 2详情 3编辑 4删除 5审批
      switch (type) {
        case 1:
        case 3:
          this.handleGoPage(type, row.order_out_no, row.is_refer);
          break;
        case 2:
          this.handleGoPage(type, row.order_out_no, row.is_refer);
          break;
        case 4:
          this.$Modal.confirm({
            title: "确认删除？",
            content: "此操作无法恢复，请确认！",
            onOk: () => {
              this.axios({
                method: "get",
                url: "/api/warehouse_order_out_del",
                params: {
                  order_out_no: row.order_out_no,
                },
              })
                .then((res) => {
                  if (res.code == 200) {
                    this.$Message.success(res.msg);
                    this.initData();
                  }
                })
                .catch((err) => {});
            },
            onCancel: () => {},
          });
          break;
        case 5:
          this.$Modal.confirm({
            title: row.state == 1 ? "确认弃审？" : "确认审批？",
            onOk: () => {
              this.axios({
                method: "get",
                url: "/api/warehouse_order_out_check",
                params: {
                  order_out_no: row.order_out_no,
                  state: row.state == 1 ? 0 : 1,
                },
              })
                .then((res) => {
                  // this.$Message.success(res.msg)
                  if (res.code == 200) {
                    this.initData();
                  }
                })
                .catch((err) => {});
            },
            onCancel: () => {},
          });
          break;
      }
    },
    handleGoPage(type, order_out_no, is_refer) {
      if (type == 1 || type == 3) {
        this.$router.push({
          path: "/cms/PurchasingManage/OutstockOrder/edit",
          query: {
            type,
            order_out_no,
            is_refer,
          },
        });
      } else {
        this.$router.push({
          path: "/cms/PurchasingManage/OutstockOrder/detail",
          query: {
            order_out_no,
          },
        });
      }
    },
    changeSize(e) {
      this.pageSize = e;
      this.initData();
    },
    changePage(e) {
      this.pageIndex = e;
      this.initData(this.newSearchData);
    },
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // beforeRouteLeave(to, from, next) {
  //   if (
  //     to.path == "/cms/PurchasingManage/OutstockOrder/detail" ||
  //     to.path == "/cms/PurchasingManage/OutstockOrder/edit"
  //   ) {
  //     next();
  //   } else {
  //     from.meta.keepAlive = false;
  //     next();
  //   }
  // },
  beforeRouteLeave(to, from, next) {
    if (to.path == "/cms/PurchasingManage/OutstockOrder/detail") {
      localStorage.setItem("searchData", JSON.stringify(this.searchData));
      localStorage.setItem("pageIndex", this.pageIndex);
      next();
    } else if (to.path == "/cms/PurchasingManage/OutstockOrder/edit") {
      localStorage.setItem("searchData", JSON.stringify(this.searchData));
      if (to.query.type == 3) {
        localStorage.setItem("pageIndex", this.pageIndex);
        localStorage.setItem("searchData", JSON.stringify(this.searchData));
      } else {
        let form = this.newSearchData;
        Object.keys(form).forEach((key) => (form[key] = ""));
        localStorage.setItem("searchData", form);
        localStorage.setItem("newSearchData", form);
        localStorage.setItem("pageIndex", 1);
        localStorage.removeItem("searchData");
        localStorage.removeItem("pageIndex");
        localStorage.removeItem("newSearchData");
      }
      next();
    } else {
      localStorage.removeItem("searchData");
      localStorage.removeItem("pageIndex");
      next();
    }
  },
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>

<style lang='scss' scoped>
.addBtn {
  display: flex;
  flex-direction: row-reverse;
}
.instock_order {
  height: 100%;
}
.instock_order_search {
  padding-top: 20px;
  /deep/.ivu-form {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  /deep/.ivu-form-item {
    display: inline-block;
    width: 250px;
  }
}
.instock_order_content {
  height: 85%;
  overflow: auto;
  .instock_order_content_btn {
    display: flex;
    justify-content: flex-end;
  }
}
.instock_order_content_page {
  display: flex;
  justify-content: center;
  padding-top: 20px;
}
.instock_order_content_table {
  margin-top: 10px;
}
</style>
