<!--
  - Author: gn
  -->
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page="page"
        :data="tableData"
        :search.sync="searchForm"
        :table-loading="tableLoading"
        :option="tableOption"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="updateOne"
        @row-save="saveOne"
        @row-del="deleteOne"
        @selection-change="selectionChange1"
      >
        <!-- @on-load="getList" -->

        <template slot="orderStatus" slot-scope="scope">
          <span v-if="scope.row.orderStatus == '0'" style="color:#00a8f3">待发货</span>
          <span v-else-if="scope.row.orderStatus == '1'" style="color:#0ed145">已发货</span>
          <span v-else-if="scope.row.orderStatus == '2'" style="color:#e04046">取消</span>
        </template>

        <template slot-scope="scope" slot="menuLeft">
          <el-button
            v-if="order_add"
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="handleAdd"
          >添加</el-button>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-download"
            @click="exportRow"
          >导出</el-button>
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button
            v-if="order_edit"
            type="text"
            size="small"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row, scope.index)"
          >编辑</el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            @click="handleDetail(scope.row, scope.index)"
          >详情</el-button>
          <el-button
            v-if="order_del"
            type="text"
            size="small"
            icon="el-icon-delete"
            @click="handleDelete(scope.row, scope.index)"
          >撤销</el-button>
        </template>
      </avue-crud>
    </basic-container>
    <Modal ref="modalRef" :width="width" @ok="refreshChange" />

    <ModalView ref="modalViewRef" />
  </div>
</template>

<script>
import { GnTableMixin } from "@/util/GnTableMixin";
import {
  fetchList,
  addResult,
  getResult,
  delResult,
  putResult,
  exportResult
} from "@/api/commonApis";
import fileDownload from "js-file-download";
import Modal from "./components/modal";
import { nowFormatTime1, nowFormatTime2 } from "@/util/GnUtils";
import ModalView from "./components/modalView";

export default {
  name: "warehouse",
  mixins: [GnTableMixin],
  components: {
    Modal,
    ModalView
  },
  data() {
    return {
      // url
      url: {
        // 共用方法和命名
        getList: "/invtory/invgoodsorder/page",
        deleteOne: "/invtory/invgoodsorder",
        getdetail: "/invtory/invgoodsorder/getGoodsByOrderNo",
        exportRow: '/invtory/invgoodsorder/export',
      },
      // 页面的 selfOption
      selfOption: {
        menuWidth: 200,
        selection: true,
        reserveSelection: true,
        column: [
          {
            type: "input",
            overHidden: true,
            label: "ID",
            prop: "orderId",
            span: 12,
            hide: true,
            display: false
          },
          {
            type: "input",
            overHidden: true,
            label: "订单号",
            prop: "orderNo",
            span: 12,
            search: true,
            addDisplay: false,
            width: 140
          },
          {
            type: "input",
            overHidden: true,
            label: "客户",
            prop: "custName",
            search: true,
            width: 180,
            span: 12
          },
          {
            label: "商品类型",
            prop: "goodsName",
            span: 12,
            type: "select",
            overHidden: true,
            multiple: true,
            dicUrl: "/invtory/invgoodstype/getAllGoodsType",
            props: {
              label: "goodsTypeName",
              value: "goodsTypeNo"
            }
          },
          {
            type: "number",
            overHidden: true,
            label: "订单数量",
            prop: "orderQyt",
            span: 12,
            width: 80
          },
          {
            type: "number",
            overHidden: true,
            precision: 2,
            label: "订单金额",
            prop: "totalPrice",
            span: 12,
            width: 120
          },

          {
            type: "date",
            overHidden: true,
            label: "订单日期",
            prop: "orderDate",
            search: true,
            searchSpan: 12,
            width: 80,
            labelWidth: 100,
            searchRange: true,
            rangeSeparator: "~",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd"
          },
          {
            type: "select",
            overHidden: true,
            label: "订单状态",
            prop: "orderStatus",
            span: 12,
            // 0-待发货,1-已发货,2-取消
            dicData: [
              { value: "0", label: "待发货" },
              { value: "1", label: "已发货" },
              { value: "2", label: "取消" }
            ],
            width: 80,
            slot: true,
            search: true
          },
          {
            type: "input",
            overHidden: true,
            label: "快递单号",
            prop: "courierNumber",
            span: 12
          },
          {
            type: "date",
            overHidden: true,
            label: "发货日期",
            prop: "sendGoodsDate",
            span: 12
          },
          {
            type: "textarea",
            overHidden: true,
            label: "备注",
            prop: "remark",
            disabled: true,
            addDisplay: false,
            hide: true,
            span: 24
          },
          {
            type: "date",
            overHidden: true,
            label: "创建时间",
            prop: "crteTime",
            span: 12,
            disabled: true,
            addDisplay: false
          },
          {
            type: "input",
            overHidden: true,
            label: "创建者",
            prop: "crteUser",
            span: 12,
            disabled: true,
            addDisplay: false
          },
          {
            type: "date",
            overHidden: true,
            label: "最后更新时间",
            prop: "upteTime",
            span: 12,
            hide: true,
            disabled: true,
            addDisplay: false
          },
          {
            type: "input",
            overHidden: true,
            label: "最后更新用户",
            prop: "upteUser",
            span: 12,
            hide: true,
            disabled: true,
            addDisplay: false
          }
        ],
        addBtn: false,
        editBtn: false,
        delBtn: false
      },

      width: "80%"
    };
  },
  watch: {},
  computed: {},
  created() {
    // this.ware_add = this.permissions['stor_add']
    // this.ware_edit = this.permissions['stor_edit']
    // this.ware_del = this.permissions['stor_del']
    // console.log("ware权限增改删", this.permissions['stor_add'], this.permissions['stor_edit'], this.permissions['stor_del']);
    this.order_add = this.permissions["order_add"] || true;
    this.order_audit = this.permissions["order_audit"] || true;
    this.order_edit = this.permissions["order_edit"] || true;
    this.order_del = this.permissions["order_del"] || true;
    this.mergeOption();
  },
  methods: {
    mergeOption() {
      this.tableOption = Object.assign(this.tableOption, this.selfOption);
      this.getList();
    },
    getList(current, params) {
      this.tableLoading = true;
      if (current) {
        this.page.currentPage = current;
      }
      if (params) {
        this.searchForm = Object.assign(this.searchForm, params);
      }
      fetchList(
        this.url.getList,
        Object.assign(
          {
            current: this.page.currentPage,
            size: this.page.pageSize
          },
          this.searchForm
        )
      )
        .then(res => {
          this.tableData = res.data.data.records;
          this.page.total = res.data.data.total;
          this.tableLoading = false;
        })
        .catch(err => {
          this.$message.error("获取表格数据错误！原因：" + err);
          this.tableLoading = false;
          this.tableData = [];
          this.page.total = 0;
        });
    },
    // 表格选中事件
    selectionChange1(selectionRows) {
      if (selectionRows.length) {
        if (selectionRows.length > 1) {
          const nowVal = selectionRows.shift();
          this.$refs.crud.toggleRowSelection(nowVal, false);
        } else if (selectionRows.length === 1) {
          this.selectionRows = selectionRows
        } else {
          this.$message.warning("只能选择一条数据!");
        }
      }
    },
    // 导出
    exportRow() {
      if(!this.selectionRows.length) {
        this.$message.warning("请选择需要导出的记录！")
        return
      }
      this.daochushuju(this.selectionRows[0])
    },
    async daochushuju(row){
      let time = nowFormatTime1()
      await exportResult(`${this.url.exportRow}?orderNo=${row.orderNo}`, {}).then(res => {
        
        return fileDownload(res.data, "订单明细" + time +'.xlsx');
      });
    },

    handleAdd() {
      let params = {};
      // params.logo = '/company/logo.png'
      // params.createTime = nowFormatTime1()
      params.orderDate = nowFormatTime2();
      this.$refs.modalRef.init(params, "add");
    },
    async handleUpdate(row, index) {
      let params;
      await getResult(this.url.getdetail, row.orderNo)
        .then(res => {
          params = res.data.data;
        })
        .catch(err => {
          this.$message.error("获取订单明细错误，请稍后再试！");
          return;
        });
      // params.logo = 'company/logo.png'
      this.$refs.modalRef.init(params, "edit");
    },
    async handleDetail(row, index) {
      let obj = {
        form: {},
        cardsData: []
      };
      await getResult(this.url.getdetail, row.orderNo)
        .then(res => {
          obj.form = res.data.data;
        })
        .catch(err => {
          this.$message.error("获取订单明细错误，请稍后再试！");
          return;
        });
      console.log("form", obj.form);
      obj.form.goodsNoList = obj.form.goodsNo;
      obj.form.goodsNoList.forEach((item, index) => {
        this.addOnetoCardsData(item, index, obj);
      });
      this.$refs.modalViewRef.init(obj);
    },

    async addOnetoCardsData(val, index, obj) {
      let obj1 = {
        goodsTypeNo: val,
        goodName: obj.form.goodsName[index],
        tableData: [],
        cardTableOption: JSON.parse(
          JSON.stringify(this.$refs.modalRef.cardTableOption)
        )
      };
      obj1.cardTableOption.menu = false;
      obj1.cardTableOption.border = false;
      obj1.cardTableOption.addRowBtn = false;
      obj1.cardTableOption.column.forEach(ii => {
        if (ii.prop === "goodsNo") {
          ii.prop = "goodsName";
        }
        if (ii.slot === true) {
          delete ii.slot;
        }
      });
      let temp = obj.form.goodsOrderTypeVoMap.find(i => i.goodsTypeNo === val);
      Object.keys(JSON.parse(temp.goodsDealList[0].goodsProp)).forEach(i => {
        let oo = {};
        oo.prop = i;
        oo.label = i;
        obj1.cardTableOption.column
          .find(i => i.prop === "goodsSpecifications")
          .children.push(oo);
      });
      obj1.tableData = temp.goodsDealList.map((i, k) => {
        i = Object.assign(i, JSON.parse(temp.goodsDealList[k].goodsProp));
        return i;
      });
      obj.cardsData.push(obj1);
    },

    handleDelete(row, index) {
      let self = this;
      this.$confirm(
        "是否确认删除订单号为 " + row.orderNo + " 的数据！",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delResult(self.url.deleteOne, row.orderId);
        })
        .then(res => {
          if (res.data.code === 0) {
            self.$message.success("删除成功！");
            self.getList();
          } else {
            self.$message.warning("删除失败！原因：" + res.data.message);
          }
        })
        .catch(err => {
          self.$message.error("错误！原因：" + err);
        });
    }
  }
};
</script>