import { mapGetters } from "vuex";
import * as API from "api/virtual/orders";

export default {
  components: {
    BTable: resolve => require(["components/table"], resolve)
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    source: {
      type: Number,
      default: 0
    },
    type: {
      type: Number,
      default: 0
    },
    orderObj: {
      type: Object,
      default: null
    }
  },
  computed: {
    filterNoUsedTotal() {
      return this.filterOrders.reduce((acc, cur) => {
        return acc + cur.counts - cur.shipments - cur.refunds;
      }, 0);
    },
    filterTotal() {
      return this.filterOrders.reduce((acc, cur) => {
        return acc + cur.counts;
      }, 0);
    },
    total() {
      return this.orders.reduce((acc, cur) => {
        return acc + cur.counts;
      }, 0);
    },
    ...mapGetters([
      "orders",
      "cards",
      "selected",
      "selectedMapped",
      "counts",
      "getFilterUsedCards",
      "getSelectedByOrderId",
      "relations",
      "relationObj",
      "real_companies",
      "real_packages"
    ])
  },
  data() {
    return {
      my_show: false,
      loading: false,
      orderLoading: false,
      cardLoading: false,
      page: {
        total: 0,
        limit: 10,
        page: 1
      },
      orderTypes: [
        "销售",
        "续费",
        "续费包",
        "加油包",
        "可选包",
        "附加包",
        "组合包"
      ],
      params: {
        sn: "",
        order_type: "",
        company_name: "",
        package_name: "",
        carrier_operator: "",
        transaction_no: "",
        pay_channel_name: "",
        business_type: "",
        time: [
          this.moment()
            .subtract("1", "months")
            .startOf("month")
            .format("YYYY-MM-DD"),
          this.moment()
            .subtract("1", "months")
            .endOf("month")
            .format("YYYY-MM-DD")
        ],
        used: "",
        sim: ""
      },
      sortChecked: false,
      vdChecked: true,
      filterOrders: [],
      showOrders: [],
      showCards: [],
      orderColumns: [
        {
          type: "expand",
          width: 50,
          render: (h, context) => {
            let row = context.row;

            let html = [];

            let col = [];

            col.push(
              h("Col", { props: { span: 8 }, class: [] }, "订单编号: " + row.sn)
            );
            col.push(
              h(
                "Col",
                { props: { span: 8 }, class: [] },
                "支付流水号: " + row.transaction_no
              )
            );
            html.push(h("Row", { class: [] }, col));

            if (this.type === 0) {
              col = [];

              col.push(
                h(
                  "Col",
                  { props: { span: 8 }, class: [] },
                  "收货人: " + row.contacts
                )
              );
              col.push(
                h(
                  "Col",
                  { props: { span: 8 }, class: [] },
                  "联系电话: " + row.mobile
                )
              );
              html.push(h("Row", { class: [] }, col));

              col = [];
              col.push(
                h(
                  "Col",
                  { props: { span: 16 }, class: [] },
                  "收货地址: " + row.address
                )
              );
              html.push(h("Row", { class: [] }, col));
            }

            if (this.type !== 0) {
              col = [];
              col.push(
                h(
                  "Col",
                  { props: { span: 16 }, class: [] },
                  "业务类型: " + row.business_type_name
                )
              );
              html.push(h("Row", { class: [] }, col));
            }

            return h("div", { class: ["fz-13"] }, html);
          }
        },
        {
          width: 60,
          align: "center",
          renderHeader: (h, context) => {
            let value = false;
            let indeterminate = false;

            value = !!this.counts;
            indeterminate = this.total !== this.counts;

            return h("Checkbox", {
              props: {
                indeterminate: value && indeterminate,
                value: value
              },
              on: {
                input: value => {
                  let order_id = this.showOrders
                    .filter(el => {
                      return el.counts - el.shipments - el.refunds > 0;
                    })
                    .map(item => {
                      return item.id;
                    });

                  this.handleSelectOrder(order_id, value);
                }
              }
            });
          },
          render: (h, context) => {
            let select = this.getSelectedByOrderId(context.row.id);

            let value = !!select.length;

            let indeterminate =
              select.length &&
              context.row.counts !==
                select.reduce((acc, cur) => {
                  return acc + cur.counts;
                }, 0);

            return h("Checkbox", {
              props: {
                indeterminate: value && !!indeterminate,
                value: value,
                disabled:
                  context.row.counts -
                    context.row.shipments -
                    context.row.refunds <=
                  0
              },
              on: {
                input: value => {
                  this.handleSelectOrder(context.row.id, value);
                }
              }
            });
          }
        },
        {
          title: "ID",
          key: "id",
          width: 80,
          sortable: true
        },
        {
          title: "订单类型",
          key: "",
          width: 90,
          render: (h, context) => {
            return h("span", this.orderTypes[context.row.type]);
          }
        },
        {
          title: "企业名称",
          key: "company_name",
          width: 210,
          sortable: true
        },
        {
          title: "运营商",
          key: "carrier_operator_name",
          width: 80
        },
        {
          title: "套餐名称",
          key: "package_name",
          width: 150,
          sortable: true
        },
        {
          title: "支付方式",
          key: "pay_channel_name",
          width: 90
        },
        {
          title: "可用量",
          key: "",
          width: 90,
          render: (h, context) => {
            return h(
              "span",
              context.row.counts - context.row.shipments - context.row.refunds
            );
          }
        },
        {
          title: "总量",
          key: "counts",
          width: 100,
          sortable: true
        },
        {
          title: "订单金额",
          key: "total_price",
          width: 120,
          sortable: true
        },
        {
          title: "下单时间",
          key: "order_at",
          minWidth: 110,
          sortable: true,
          render: (h, context) => {
            return h(
              "span",
              this.moment(context.row.order_at).format("YYYY-MM-DD")
            );
          }
        },
        {
          title: "所需卡量",
          key: "",
          width: 150,
          fixed: "right",
          render: (h, context) => {
            let select = this.getSelectedByOrderId(context.row.id);

            let value = select.length
              ? select.reduce((acc, cur) => {
                  return acc + cur.counts;
                }, 0)
              : 0;

            return h("InputNumber", {
              props: {
                max:
                  context.row.counts -
                  context.row.shipments -
                  context.row.refunds,
                min: 0,
                value: value,
                precision: 0
              },
              on: {
                input: value => {
                  let bool = !!value;
                  this.handleSelectOrder(context.row.id, bool, value);
                }
              }
            });
          }
        }
      ],
      cardColumns: [
        {
          width: 60,
          align: "center",
          renderHeader: (h, context) => {
            let value = false;
            let indeterminate = false;

            value = !!this.selectedMapped.length;

            indeterminate =
              this.selectedMapped.length &&
              this.selectedMapped.length !== this.showCards.length;
            return h("Checkbox", {
              props: {
                indeterminate: value && indeterminate,
                value: value
              },
              on: {
                input: value => {
                  if (value) {
                    let cards = this.getFilterUsedCards(this.showCards);
                    cards = this.getFilterDiffComPacCards(cards);
                    this.$store.dispatch("pushSelected", cards);
                  } else {
                    this.$store.dispatch("removeSelected", this.showCards);
                  }
                }
              }
            });
          },
          render: (h, context) => {
            let value =
              this.selectedMapped.indexOf(context.row._rowIndex) !== -1;

            let disabled = Boolean(
              context.row.virtual_order_id || context.row.refunded_at
            );

            if (this.isDiffCompany(context.row)) {
              disabled = true;
            }

            return h("Checkbox", {
              props: {
                value: value,
                disabled: disabled
              },
              on: {
                input: value => {
                  let action = value ? "pushSelected" : "removeSelected";
                  this.$store.dispatch(action, [context.row]);
                }
              }
            });
          }
        },
        {
          title: "SIM",
          key: "sim",
          width: 135
        },
        {
          title: "状态",
          key: "",
          width: 100,
          render: (h, { row, column, index }) => {
            let color = "success";
            let status_name = "未使用";

            if (row.refunded_at && row.virtual_order_id) {
              color = "error";
              status_name = "退货使用";
            } else if (row.virtual_order_id) {
              color = "primary";
              status_name = "已使用";
            } else if (row.refunded_at) {
              color = "warning";
              status_name = "已退货";
            }

            if (this.isDiffCompany(row)) {
              color = "error";
              status_name = "不可用";
            }

            return h(
              "Tag",
              {
                props: {
                  color: color
                }
              },
              status_name
            );
          }
        },
        {
          title: "数量",
          key: "counts",
          width: 60
        },
        {
          title: "VD企业",
          key: "company_name",
          width: 210
        },
        {
          title: "VD套餐",
          key: "package_name",
          width: 150
        },
        {
          title: "VD套餐编号",
          key: "package_sn",
          width: 150
        }
      ]
    };
  },
  watch: {
    show(bool) {
      this.my_show = bool;
      this.$store.commit("SET_CARDS", []);
      if (bool) {
        this.params.type = this.type;
        if (this.orderObj) {
          this.params.carrier_operator = this.orderObj.carrier_operator;
          // this.params.package_name = this.orderObj.package_name;
        }
        this.index();
      }
    }
  },
  methods: {
    index(force = 0) {
      if (this.params.type != this.type) {
        this.params.type = this.type;
        this.$store.dispatch("initOrder");
      }

      let params = this.parseParams({
        time: this.params.time,
        type: this.params.type
      });

      if (this.orderObj && this.vdChecked && this.type !== 0) {
        params.virtual_company_id = this.orderObj.company_id;
      }

      if (force) {
        this.$store.commit("SET_ORDER_PARAMS", {});
        params.skipCache = 1;
      }

      this.orderLoading = true;

      if (this.params.sim !== "") {
        params.sim = this.params.sim;
        let cardParams = { type: this.type, sim: this.params.sim };
        cardParams = this.transformerParams(cardParams);
        this.params.time = [];
        this.cardLoading = true;
        this.$store
          .dispatch("getCardsByParams", cardParams)
          .then(cards => {
            this.showCards = cards;
            this.cardLoading = false;
          })
          .catch(() => {
            this.cardLoading = false;
          });
      }

      params = this.transformerParams(params);

      this.$store
        .dispatch("getOrders", params)
        .then(() => {
          if (this.relationObj && this.relationObj.virtual_company_id) {
            this.sortChecked = true;
            this.sortOrders("updated_at");
          } else {
            this.sortChecked = false;
            this.sortOrders("order_at");
          }
          this.orderLoading = false;
        })
        .catch(() => {
          this.orderLoading = false;
        });
    },
    changeSortChecked(value) {
      let action = value ? "updated_at" : "order_at";
      this.sortOrders(action);
    },
    changeLimit(limit) {
      this.page.limit = limit;
      this.changePage(1);
    },
    changePage(page) {
      this.page.page = page;

      let filterOrders = JSON.parse(JSON.stringify(this.orders));

      if (
        this.params.company_name !== "" &&
        this.params.company_name !== undefined
      ) {
        filterOrders = filterOrders.filter(el => {
          return (
            el.company_name &&
            el.company_name.indexOf(this.params.company_name) !== -1
          );
        });
      }

      if (
        this.params.package_name !== "" &&
        this.params.package_name !== undefined
      ) {
        filterOrders = filterOrders.filter(el => {
          return (
            el.package_name &&
            el.package_name.indexOf(this.params.package_name) !== -1
          );
        });
      }

      if (
        this.params.pay_channel_name !== "" &&
        this.params.pay_channel_name !== undefined
      ) {
        filterOrders = filterOrders.filter(el => {
          return (
            el.pay_channel_name &&
            el.pay_channel_name.indexOf(this.params.pay_channel_name) !== -1
          );
        });
      }

      if (
        this.params.transaction_no !== "" &&
        this.params.transaction_no !== undefined
      ) {
        filterOrders = filterOrders.filter(el => {
          return (
            el.transaction_no &&
            el.transaction_no.indexOf(this.params.transaction_no) !== -1
          );
        });
      }

      if (this.params.sn !== "" && this.params.sn !== undefined) {
        filterOrders = filterOrders.filter(el => {
          return el.sn && el.sn.indexOf(this.params.sn) !== -1;
        });
      }

      if (
        this.params.business_type !== "" &&
        this.params.business_type !== undefined
      ) {
        filterOrders = filterOrders.filter(el => {
          return el.business_type === this.params.business_type;
        });
      }

      if (
        this.params.order_type !== "" &&
        this.params.order_type !== undefined
      ) {
        filterOrders = filterOrders.filter(el => {
          return el.type === this.params.order_type;
        });
      }

      if (
        this.params.carrier_operator !== "" &&
        this.params.carrier_operator !== undefined
      ) {
        filterOrders = filterOrders.filter(el => {
          return el.carrier_operator === this.params.carrier_operator;
        });
      }

      if (this.params.used !== "" && this.params.used !== undefined) {
        filterOrders = filterOrders.filter(el => {
          switch (this.params.used) {
            case 0:
              return el.shipments + el.refunds === 0 && el.counts;
            case 1:
              return (
                el.shipments + el.refunds > 0 &&
                el.shipments + el.refunds !== el.counts
              );
            case 2:
              return el.shipments + el.refunds === el.counts;
            default:
              break;
          }
        });
      }

      this.page.total = filterOrders.length;

      this.filterOrders = filterOrders;

      this.showOrders = filterOrders.slice(
        (page - 1) * this.page.limit,
        page * this.page.limit
      );
    },
    handleOrderRowDblclick(row) {
      this.getCards(row.id);
    },
    visibleChange(bool) {
      if (!bool) {
        this.$emit("update:show", false);
      }
    },
    close() {
      this.clearParams();
      this.my_show = false;
      this.$store.commit("SET_RELATION_OBJ", {});
    },
    clearParams() {
      this.params = {
        sn: "",
        company_name: "",
        package_name: "",
        carrier_operator: "",
        transaction_no: "",
        pay_channel_name: "",
        business_type: "",
        time: [
          this.moment()
            .subtract("1", "months")
            .startOf("month")
            .format("YYYY-MM-DD"),
          this.moment()
            .subtract("1", "months")
            .endOf("month")
            .format("YYYY-MM-DD")
        ],
        used: "",
        sim: ""
      };
    },
    clear() {
      this.clearParams();
      this.showCards = [];
      this.$store.dispatch("initOrder");
    },
    clearSelect() {
      this.$store.dispatch("setSelected", []);
    },
    exportOrders() {
      let columns = [
        { title: "订单编号", key: "sn" },
        { title: "订单类型", key: "order_type" },
        { title: "企业名称", key: "company_name" },
        { title: "运营商", key: "carrier_operator_name" },
        { title: "套餐名称", key: "package_name" },
        { title: "支付方式", key: "pay_channel_name" },
        { title: "支付流水号", key: "transaction_no" },
        { title: "订单时间", key: "order_at" },
        { title: "SIM", key: "sim" },
        { title: "单价", key: "unit_price" },
        { title: "数量", key: "counts" },
        { title: "金额", key: "total_price" },
        { title: "使用状态", key: "virtual_order_id" },
        { title: "VD企业", key: "virtual_company_name" },
        { title: "VD套餐", key: "virtual_package_name" },
        { title: "VD编号", key: "virtual_package_sn" }
      ];

      if (this.type !== 0) {
        columns.splice(5, 0, { title: "业务类型", key: "business_type_name" });
      }

      if (this.type === 0) {
        columns.push({ title: "退货", key: "refunded" });
      }

      let data = [];

      let orders = {};

      for (let index = 0; index < this.orders.length; index++) {
        const element = this.orders[index];
        orders[element.id] = element;
      }

      for (let index = 0; index < this.cards.length; index++) {
        const element = this.cards[index];
        let order = orders[element.order_id];

        let obj = {
          sn: order.sn + "\t",
          order_type: this.orderTypes[order.type],
          company_name: order.company_name,
          carrier_operator_name: order.carrier_operator_name,
          package_name: order.package_name,
          pay_channel_name: order.pay_channel_name,
          transaction_no: order.transaction_no + "\t",
          order_at: order.order_at,
          sim: element.sim + "\t",
          unit_price: order.unit_price,
          counts: element.counts,
          total_price: order.unit_price * element.counts,
          virtual_order_id: element.virtual_order_id ? "已使用" : "未使用",
          virtual_company_name: element.company_name,
          virtual_package_name: element.package_name,
          virtual_package_sn: element.package_sn
        };

        if (this.type !== 0) {
          obj.business_type_name = order.business_type_name;
        }

        if (this.type === 0) {
          obj.refunded = element.refunded_at ? "是" : "否";
        }

        data.push(obj);
      }

      this.$refs.cardSelection.exportCsv({
        filename: "订单导出" + this.moment().format("YYYYMMDDhhmmss"),
        columns: columns,
        data: data
      });
    },
    cannel() {
      this.clear();
      this.close();
    },
    resetParams() {
      for (let k in this.params) {
        if (k === "time") {
          this.params[k] = [
            this.moment()
              .subtract("1", "months")
              .startOf("month")
              .format("YYYY-MM-DD"),
            this.moment()
              .subtract("1", "months")
              .endOf("month")
              .format("YYYY-MM-DD")
          ];
        } else {
          this.params[k] = "";
        }
      }
    },
    resetSearch() {
      this.resetParams();
      this.$store.dispatch("initOrder");
      this.index(1);
    },
    getCards(order_id) {
      this.cardLoading = true;
      return new Promise(resolve => {
        let params = { order_id: order_id, type: this.type };
        params = this.transformerParams(params);
        this.$store
          .dispatch("getCards", params)
          .then(cards => {
            this.cardLoading = false;
            this.showCards = cards;
            resolve(cards);
          })
          .catch(err => {
            this.cardLoading = false;
          });
      });
    },
    handleSelectOrder(order_id, value, counts = null) {
      this.$store.dispatch("removeSelectedByOrderId", order_id);

      if (!value) {
        return;
      }

      this.getCards(order_id).then(cards => {
        cards = this.getFilterUsedCards(cards);
        cards = this.getFilterDiffComPacCards(cards);

        if (!cards.length) {
          return this.$Message.error("所有卡都不可使用");
        }

        cards.sort((a, b) => {
          return a.counts < b.counts ? -1 : a.counts > b.counts ? 1 : 0;
        });

        let arr = cards.map(item => {
          return JSON.parse(JSON.stringify(item));
        });

        if (counts !== null) {
          let acc = 0;

          arr = arr.filter(item => {
            acc += item.counts;
            return acc <= counts;
          });
        }

        this.$store.dispatch("pushSelected", arr);
      });
    },
    order() {
      if (
        this.selected.findIndex(el => {
          return el.virtual_order_id !== 0;
        }) !== -1
      ) {
        return this.$Message.error("所选数据存在已使用的卡");
      }

      if (!this.selected.length) {
        return this.$Message.error("未选择卡");
      }

      if (this.type !== 0) {
        let group = {};

        for (let index = 0; index < this.selectedMapped.length; index++) {
          const element = this.selected[index];
          let key = element.company_id + "_" + element.package_id;

          if (group.hasOwnProperty(key)) {
            group[key].push(element);
          } else {
            group[key] = [element];
          }
        }

        if (Object.keys(group).length >= 1) {
          this.$store.commit("SET_ORDER_GROUP", group);
        }
      }

      this.$emit("create-order");
      this.clearParams();
    },
    store() {
      if (!this.orderObj) {
        return this.$Message.error("订单错误");
      }

      if (this.orderObj.counts !== this.counts) {
        return this.$Message.error("选择的卡数量不正确");
      }

      if (this.type !== 0) {
        for (let index = 0; index < this.selected.length; index++) {
          const element = this.selected[index];
          if (element.company_id !== this.orderObj.company_id) {
            return this.$Message.error("所选卡原企业与订单企业不匹配");
          }
        }
      }

      let params = {};
      params.type = this.type;
      params.selected = this.selected.map(el => {
        return { order_id: el.order_id, counts: el.counts, sim: el.sim };
      });

      this.loading = true;

      // 编辑
      API.update(params, this.orderObj.id)
        .then(res => {
          this.loading = false;
          if (res.code == 0) {
            this.$emit("store-success");
            this.$Message.success("操作成功");
            this.clear();
          }
        })
        .catch(err => {
          this.loading = false;
        });
    },
    sort() {
      this.showCards = this.cards;

      let mapped = this.orders.map((el, i) => {
        return { index: i, id: el.id };
      });

      mapped.sort((a, b) => {
        let ac = this.getSelectedByOrderId(a.id).reduce((acc, cur) => {
          return acc + cur.counts;
        }, 0);
        let bc = this.getSelectedByOrderId(b.id).reduce((acc, cur) => {
          return acc + cur.counts;
        }, 0);
        return ac > bc ? -1 : ac < bc ? 1 : 0;
      });

      let orders = mapped.map(el => {
        return this.orders[el.index];
      });

      this.$store.commit("SET_REAL_ORDERS", orders);
      this.resetParams();
      this.changePage(1);
    },
    sortOrders(sortBy = "updated_at") {
      let mapped = [];

      if (sortBy === "order_at") {
        mapped = this.orders.map((el, i) => {
          return { index: i, order_at: el.order_at };
        });

        mapped.sort((a, b) => {
          if (a.counts - a.shipments - a.refunds <= 0) {
            return -1;
          }

          return a.order_at > b.order_at ? -1 : a.order_at < b.order_at ? 1 : 0;
        });
      } else {
        let virtual_company_id = this.relationObj.virtual_company_id;
        let virtual_package_id = this.relationObj.virtual_package_id;

        let relations = this.relations;

        let sortRules = relations.filter(el => {
          if (
            virtual_company_id == el.virtual_company_id ||
            virtual_package_id == el.virtual_package_id
          ) {
            return true;
          }

          return false;
        });

        mapped = this.orders.map((el, i) => {
          let display = -1;

          for (let index = 0; index < sortRules.length; index++) {
            const element = sortRules[index];
            if (
              element.real_company_id == el.company_id &&
              element.real_package_id == el.package_id
            ) {
              display = element[sortBy];
            } else if (element.real_company_id == el.company_id) {
              display = 0;
            }
          }

          return { index: i, display };
        });

        mapped.sort((a, b) => {
          return a.display > b.display ? -1 : a.display < b.display ? 1 : 0;
        });
      }

      let orders = mapped.map(el => {
        return this.orders[el.index];
      });

      this.$store.commit("SET_REAL_ORDERS", orders);

      this.changePage(1);
    },
    selectAll() {
      let order_id = this.filterOrders
        .filter(el => {
          return el.counts - el.shipments - el.refunds >= 0;
        })
        .map(item => {
          return item.id;
        });

      if (this.filterTotal > 200000) {
        return this.$Message.error("当前请求数据量过大，请筛选过滤后查询");
      }

      this.handleSelectOrder(order_id, true);
    },
    isDiffCompany(obj) {
      if (
        this.type != 0 &&
        this.orderObj &&
        this.vdChecked &&
        obj.company_id !== this.orderObj.company_id
      ) {
        return true;
      }

      return false;
    },
    getFilterDiffComPacCards(cards) {
      return cards.filter(item => !this.isDiffCompany(item));
    },
    transformerParams(params) {
      if (params.type === 1) {
        params.type = [1, 6];
      } else if (params.type === 3) {
        params.type = [3, 5, 6];
      }

      return params;
    }
  }
};
