<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot-scope="scope" slot="menuLeft">
        <el-button type="primary"
                   icon="el-icon-bottom"
                   size="small"
                   @click="exportExcelDelivery()">导出
        </el-button>
      </template>
    </avue-crud>
    <el-dialog :title="`【`+form.realName+`】未交割数据`"
               append-to-body
               style="margin-top: 20px"
               :visible.sync="dialogFormVisible"
               width="60%"
               height="50%">
      <avue-crud :search.sync="itemSearch"
                 :data="itemData"
                 :option="itemOption"
                 :table-loading="itemLoading"
                 :page.sync="itemPage"
                 @search-change="itemSearchChange"
                 @search-reset="itemSearchReset"
                 @selection-change="itemSelectionChange"
                 @current-change="itemCurrentChange"
                 @size-change="itemSizeChange"
                 @refresh-change="itemRefreshChange"
                 @on-load="itemOnLoad">
        <template slot-scope="scope" slot="menuLeft">
          <el-button type="danger"
                     icon="el-icon-plus"
                     size="small"
                     @click="handleDelivery()">交割
          </el-button>
        </template>
      </avue-crud>
    </el-dialog>
  </basic-container>
</template>

<script>
import {getDeliveryPage, getNoDeliveryPageByUserId, batchDelivery,expExcelDelivery} from "@/api/shopping/consign";
import {mapGetters} from "vuex";

export default {
  data() {
    return {
      dialogFormVisible: false,
      itemLoading: true,
      itemPage: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      itemSelectionList: [],
      itemSearch: {
        consignUserId: ''
      },
      itemData: [],
      itemOption: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        selection: true,
        dialogClickModal: false,
        addBtn: false,
        menu: false,
        column: [
          {
            label: "主键ID",
            prop: "id",
            hide: true,
            display: false,
          },
          {
            label: "订单ID",
            prop: "orderId",
            width: 150,
          },
          {
            label: "商品ID",
            prop: "goodsId",
            hide: true,
            display: false,
          },
          {
            label: "标题",
            prop: "title",
            width: 130,
            span: 24,
          },
          {
            label: "商品名称",
            prop: "goodsName",
            display: false,
            width: 120,
            span: 24,
          },
          {
            label: "货号",
            prop: "productNo",
            width: 100,
            hide: true,
            rules: [{
              required: true,
              message: "请输入货号",
              trigger: "blur"
            }]
          },
          {
            label: "寄售场次",
            prop: "consignConfigId",
            width: 150,
          },
          {
            label: "取得价",
            prop: "obtainPrice",
            rules: [{
              required: true,
              message: "请输入取得价",
              trigger: "blur"
            }]
          },
          {
            label: "抢购价",
            prop: "consignPrice",
            rules: [{
              required: true,
              message: "请输入抢购价",
              trigger: "blur"
            }]
          },
          {
            label: "交割价",
            prop: "deliveryPrice",
            rules: [{
              required: true,
              message: "请输入交割价",
              trigger: "blur"
            }]
          },
          {
            label: "是否交割",
            prop: "isDeliveryDisplayName",
            display: false,
          },
          {
            label: "是否交割",
            prop: "isDelivery",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=yes_no",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            dataType: "number",
            display: false,
            hide: true,
            rules: [{
              required: true,
              message: "请选择是否交割",
              trigger: "blur"
            }]
          },
          {
            label: "数量",
            prop: "totalNum",
            type: "number",
            rules: [{
              required: true,
              message: "请输入数量",
              trigger: "blur"
            }]
          },
          {
            label: "剩余数量",
            prop: "nowStock",
            type: "number",
            rules: [{
              required: true,
              message: "请输入剩余数量",
              trigger: "blur"
            }]
          },
          {
            label: "创建时间",
            prop: "createTime",
            display: false,
            width: 150,
            rules: [{
              required: true,
              message: "请输入创建时间",
              trigger: "blur"
            }]
          },
        ]
      },
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        dialogClickModal: false,
        column: [
          {
            label: "寄售用户ID",
            prop: "consignUserId",
            hide: true,
            display: false,
          },
          {
            label: "名字",
            prop: "realName",
            search: true
          },
          {
            label: "账号",
            prop: "account",
            display: false,
            search: true
          }, {
            label: "当前余额",
            prop: "nowMoney",
            display: false,
          }, {
            label: "未付款金额",
            prop: "totalNoDeliveryPrice",
            display: false,
          },
          {
            label: "总订单数",
            prop: "totalOrderNum",
            display: false,

          },
          {
            label: "总收益",
            prop: "totalIncome",
            display: false,

          },
          {
            label: "完结金额",
            prop: "totalDeliveryPrice",
            display: false,

          },
          {
            label: "完结单数",
            prop: "totalDeliveryNum",
            display: false,

          },
          {
            label: "是否完结",
            prop: "deliveryStateName",
            display: false,
          }
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: false,
        viewBtn: this.vaildData(this.permission.delivery_view, false),
        delBtn: false,
        editBtn: false,
      };
    },
    ids() {
      let ids = [];
      this.itemSelectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        this.dialogFormVisible = true
        this.itemOnLoad(this.itemPage, this.itemSearch)
      }
      // done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getDeliveryPage(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    itemSearchReset() {
      this.itemQuery = {};
      this.itemOnLoad(this.itemPage);
    },
    itemSearchChange(params, done) {
      this.itemQuery = params;
      this.itemPage.currentPage = 1;
      this.itemOnLoad(this.itemPage, params);
      done();
    },
    itemSelectionChange(list) {
      this.itemSelectionList = list;
    },
    itemSelectionClear() {
      this.itemSelectionList = [];
      this.$refs.crud.toggleSelection();
    },
    itemCurrentChange(currentPage) {
      this.itemPage.currentPage = currentPage;
    },
    itemSizeChange(pageSize) {
      this.itemPage.pageSize = pageSize;
    },
    itemRefreshChange() {
      this.itemOnLoad(this.itemPage, this.itemQuery);
    },
    itemOnLoad(page, itemParams = {}) {
      this.itemLoading = true;
      itemParams.consignUserId = this.form.consignUserId
      getNoDeliveryPageByUserId(page.currentPage, page.pageSize, Object.assign(itemParams, this.itemQuery)).then(res => {
        const data = res.data.data;
        this.itemPage.total = data.total;
        this.itemData = data.records;
        console.log("itemData", this.itemData)
        this.itemLoading = false;
        this.itemSelectionClear();
      });
    },
    handleDelivery() {
      if (this.itemSelectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      //交割金额就是抢购价
      let deliveryMoney = 0;
      let deliveryIds = [];
      this.itemSelectionList.forEach(ele => {
        deliveryMoney = deliveryMoney + ele.consignPrice,
          deliveryIds.push(ele.id)
      });
      console.log('deliveryMoney', this.itemSelectionList, '=====', 'totalIncome', this.form.totalIncome)
      let data = ((deliveryMoney / this.form.totalIncome) * 100).toFixed(2) + '%'
      this.$confirm("当前选中交割金额为" + deliveryMoney + "元,交割比例为" + data + "，确定将割?", "交割", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        batchDelivery(deliveryIds).then(()=>{
          this.itemSelectionClear()
          this.itemSearchReset();
          this.$message({
            type: "success",
            message: "交割成功!"
          });
        })
      }).catch(() => {
        this.itemSelectionClear()
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    exportExcelDelivery(){
      expExcelDelivery().then(res => {
        if (res.status===200){
          let url = window.URL.createObjectURL(new Blob([res.data]));
          let a = document.createElement('a');
          a.style.display = 'none';
          a.href = url;
          // 下面两行是自己项目需要的处理，总之就是得到下载的文件名（加后缀）即可
          var fileName = '交割数据.xlsx';
          a.setAttribute('download',fileName);
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
          this.userExportLoading = false;
          this.userExportShow = false;
          this.$message.success("文件下载成功");
        }else {
          this.$message.error("文件下载失败");
        }
      })
        .catch(err => {
          this.userExportLoading = false;
          this.$message.error(err.msg || err.message || '操作失败');
        });
    }
  }
};
</script>

<style>
</style>
