<template>
  <basic-container >
    <div v-if="!dialogble">
      <avue-data-display :option="optionblock"></avue-data-display>
      <avue-crud :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
      >
        <template slot="menuLeft">
          <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.platformconsign_delete"
            @click="handleDelete">删 除
          </el-button>
          <!-- <el-button type="success" size="small" icon="el-icon-circle-plus-outline" plain
            v-if="permission.platformconsign_pay" @click="handleBatchPay">付款
          </el-button> -->
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button type="text" icon="el-icon-view" size="small"
            @click.stop="beforeOpen(scope.row,scope.index)" v-if="permission.platformconsign_pay">查看
          </el-button>
          <el-button type="text" size="small"
                     @click.stop="allPay(scope.row,scope.index)" v-if="permission.platformconsign_pay">一键打款
          </el-button>
        </template>
      </avue-crud>
    </div>

   <div v-else style="height: 100%;">
     <avue-crud :option="option2"
                :table-loading="loading"
                :data="data2"
                :permission="permissionList"
                :search="myQuery"
                ref="crud2"
                @search-change="searchChange2"
                @selection-change="consignList = $event" >
       <template slot="menuLeft">
         <el-button size="small" icon="el-icon-arrow-left" plain
           @click.stop="back">返回
         </el-button>
         <el-button type="primary" size="small" icon="el-icon-upload2" plain
         @click.stop="payMoney"
         :loading="butLoading"
          >线上打款
         </el-button>
         <el-button type="primary" size="small" icon="el-icon-download" plain
         @click.stop="payMoneyOffline"
         :loading="butLoading"
          >线下打款
         </el-button>
       </template>
     </avue-crud>


     <el-dialog title="线下打款" :visible.sync="offlinePayShow" width="70%" append-to-body>
       <avue-crud :option="offlinePayOption" :table-loading="offlineLoading" :data="offlinePayList" :permission="permissionList"></avue-crud>
       <span slot="footer" class="dialog-footer">
         <el-button type="primary" @click="offlinePayConfirm" >确 定</el-button>
         <el-button @click="offlinePayShow = false">取 消</el-button>
       </span>
     </el-dialog>
   </div>
  </basic-container>
</template>

<script>
  import {getPlatformList,getDetail,add,update,remove,payMoneyApi, getStatistics, payMoneyOfflineApi, payMoneyOfflineConfirmApi} from "../../api/shopping/consign";
  import {
    mapGetters
  } from "vuex";

  export default {
    data() {
      return {
        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: false,
          selection: true,
          dialogClickModal: false,
          labelWidth: 120,
          column: [{
              label: "批次ID",
              prop: "consignConfigId",
              // width: 100,
              span: 24,
              overHidden: true,
            },
            {
              label: "授权订单数",
              prop: "orderNum",
              // width: 100,
              span: 24,
              overHidden: true,
            },
            {
              label: "订单单价",
              prop: "orderPrice",
              // width: 100,
              span: 24,
              overHidden: true,
            },
            {
              label: "结束时间",
              prop: "endTime",
              // width: 100,
              span: 24,
              overHidden: true,
            },
            // {
            //   label: "主键ID",
            //   prop: "id",
            //   hide: true,
            //   display: false,
            // },
            // {
            //   label: "订单ID",
            //   prop: "orderId",
            //   hide: true,
            //   display: false,
            // },
            // {
            //   label: "商品ID",
            //   prop: "goodsId",
            //   hide: true,
            //   display: false,
            // },
            // {
            //   label: "标题",
            //   prop: "title",
            //   width: 100,
            //   span: 24,
            //   overHidden: true,
            // },
            // {
            //   label: "商品名称",
            //   prop: "goodsName",
            //   display: false,
            //   width: 120,
            //   span: 24,
            // },
            // {
            //   label: "货号",
            //   prop: "productNo",
            //   width: 100,
            //   rules: [{
            //     required: true,
            //     message: "请输入货号",
            //     trigger: "blur"
            //   }]
            // },
            // {
            //   label: "场次标题",
            //   prop: "consignConfigDisplayName",
            //   width: 100,
            // },
            // {
            //   label: "寄售场次",
            //   prop: "consignConfigId",
            //   type: "select",
            //   width: 150,
            //   dicUrl: "/api/shopping/consignconfig/getList",
            //   props: {
            //     label: "title",
            //     value: "id"
            //   },
            //   hide: true,
            //   display: false,
            //   search: true,
            // },
            // {
            //   label: "寄售用户ID",
            //   prop: "consignUserId",
            //   hide: true,
            //   display: false,
            // },
            // {
            //   label: "寄售人",
            //   prop: "consignUserIdDisplayName",
            //   display: false,
            //   width: 120,
            // },
            // {
            //   label: "取得价",
            //   prop: "obtainPrice",
            // },
            // {
            //   label: "抢购价",
            //   prop: "consignPrice",
            //   rules: [{
            //     required: true,
            //     message: "请输入抢购价",
            //     trigger: "blur"
            //   }]
            // },
            // {
            //   label: "状态",
            //   prop: "consignStateDisplayName",
            //   display: false,
            // },
            // {
            //   label: "寄售状态",
            //   prop: "consignState",
            //   type: "select",
            //   dicUrl: "/api/blade-system/dict-biz/dictionary?code=consign_state",
            //   props: {
            //     label: "dictValue",
            //     value: "dictKey"
            //   },
            //   dataType: "number",
            //   hide: true,
            //   display: false,
            //   rules: [{
            //     required: true,
            //     message: "请选择寄售状态",
            //     trigger: "blur"
            //   }]
            // },
            // {
            //   label: "创建时间",
            //   prop: "createTime",
            //   display: false,
            //   width: 140,
            //   rules: [{
            //     required: true,
            //     message: "请输入创建时间",
            //     trigger: "blur"
            //   }]
            // },
          ]
        },
        data: [],
        dialogble: '',
        isAll: 0,
        myQuery: {
          isSearchAll: 0,
        },
        option2: {
          height: 'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          selection: true,
          dialogClickModal: false,
          labelWidth: 120,
          menu:false,
          column: [
            {
              label: "是否全部",
              prop: "isSearchAll",
              type: "select",
              dicUrl: "/api/blade-system/dict/dictionary?code=yes_or_no",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
              search: true,
              hide: true,
              change: ({row, value}) => {
                this.myQuery.isSearchAll = value;
              }
            },
            {
              label: "主键ID",
              prop: "id",
              hide: true,
              display: false,
            },
            {
              label: "订单ID",
              prop: "orderId",
              hide: true,
              display: false,
            },
            {
              label: "商品ID",
              prop: "goodsId",
              hide: true,
              display: false,
            },
            {
              label: "批次ID",
              prop: "consignConfigId",
              width: 200,
              span: 24,
              overHidden: true,
            },
            {
              label: "标题",
              prop: "title",
              width: 100,
              span: 24,
              overHidden: true,
            },
            {
              label: "商品名称",
              prop: "goodsName",
              display: false,
              width: 120,
              span: 24,
            },
            {
              label: "数量",
              prop: "totalNum",
              width: 100,
            },
            {
              label: "取得价",
              prop: "obtainPrice",
            },
            {
              label: "抢购价",
              prop: "consignPrice",
              display: false,
            },
            {
              label: "寄售用户名称",
              prop: "consignUserName",
            },
            {
              label: "寄售用户手机号",
              prop: "consignUserPhone",
            },
            {
              label: "开始时间",
              prop: "startTime",
            },
            {
              label: "结束时间",
              prop: "endTime",
            }
          ]
        },
        data2: [],
        consignList: [],
        dialogVisible: false,
        optionblock: {
          span: 6,
          data: [
            {
              // click: function (item) {
              //   alert(JSON.stringify(item));
              // },
              count: 0,
              title: '当前需付款数',
            },
            {
              count: 0,
              decimals: 2,
              title: '进货金额',
            },
            {
              count: 0,
              decimals: 2,
              title: '税收金额',
            },
            {
              count: 0,
              decimals: 2,
              title: '应付金额',
            }
          ]
        },
        butLoading:false,
        offlinePayShow:false,
        offlinePayList:[],
        offlineLoading: false,
        offlinePayOption: {
          height: '450',
          calcHeight: 30,
          border: true,
          menu: false,
          // tip: false,
          searchShow: false,
          // searchMenuSpan: 6,
          // selection: true,
          // dialogClickModal: false,
          // labelWidth: 120,
          column: [
            {
              label: "寄售用户ID",
              prop: "consignUserId",
              width: 200,
            },
            {
              label: "寄售用户名称",
              prop: "consignUserName",
              width: 150,
            },
            {
              label: "寄售用户手机号",
              prop: "consignUserPhone",
              width: 200,
            },
            {
              label: "单数",
              prop: "count",
            },
            {
              label: "进货总金额",
              prop: "obtainPrice",
            },
            {
              label: "寄售总金额",
              prop: "consignPrice",
            },
            {
              label: "手续费",
              prop: "procedurePrice",
            },
            {
              label: "打款金额",
              prop: "remitPrice",
            },
            {
              label: "税收金额",
              prop: "taxPrice",
            }
          ]
        }
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.platformconsign_add, false),
          viewBtn: this.vaildData(this.permission.platformconsign_view, false),
          delBtn: this.vaildData(this.permission.platformconsign_delete, false),
          editBtn: this.vaildData(this.permission.platformconsign_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    created() {
      getStatistics().then(
        res => {
          this.optionblock.data[0].count = res.data.data.allCount
          this.optionblock.data[1].count = res.data.data.obtainAmount
          this.optionblock.data[2].count = res.data.data.revenueAmount
          this.optionblock.data[3].count = res.data.data.copeAmount
        });
    },
    methods: {
      offlinePayConfirm() {
        if(this.consignList.length < 1) {
          this.$message.error('请先勾选寄售账单');
          return;
        }
        let loading = this.$loading({
          lock: true,
          text: '加载中，请稍等...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.offlineLoading = true;
        let close = () => {
          this.offlinePayShow = false;
          this.offlineLoading = false;
          loading.close();
          this.beforeOpen({consignConfigId: this.dialogble});
        }
        let new_arr = this.consignList.map(ele => ele.id);
        payMoneyOfflineConfirmApi(new_arr).then(res => {
          close();
          if(res.data.code != 200) return this.$message.error(res.msg || res.message || '操作失败');
          this.$message.success(res.msg || res.message || '操作成功')
        }).catch(err => {
          close();
          this.$message.error(err.msg || err.message || '操作失败');
        })
      },
      payMoneyOffline() {
        if(this.consignList.length < 1) {
          this.$message.error('请先勾选寄售账单');
          return;
        }
        let loading = this.$loading({
          lock: true,
          text: '加载中，请稍等...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        let new_arr = this.consignList.map(ele => ele.id);
        payMoneyOfflineApi(new_arr).then(res => {
          this.offlinePayList = res.data.data;
          this.offlinePayShow = true;
          loading.close();
        });
      },
      back() {
        this.dialogble = '';
        this.myQuery.isSearchAll = 0;
      },
      payMoney() {
        if(this.consignList.length < 1) {
          this.$message.error('请先勾选寄售账单');
          return;
        }
        this.$alert('此操作将确认打款, 请选择对应的付款途径', '选择付款方式', {
          showCancelButton: false,
          confirmButtonText: '确认付款',
          cancelButtonText: '特殊账号付款',
          callback: action => {
            this.loading = true;
            this.butLoading = true;
            if (action == 'cancel') {
              this.loading = false;
              this.butLoading = false;
              return;
            }
            let ids = this.consignList.map(ele => ele.id)
            let orderConsignIds = this.consignList;
            // let orderConsignIds = this.consignList.map(ele => ele.orderConsignId)
            let payType = action == 'confirm'? '0': '1'
            payMoneyApi(this.dialogble, ids, payType, orderConsignIds).then(res => {
              if(res.data.code != 200) this.$message.error(res.data.msg)
              else this.$message.success(res.data.msg)

              this.$refs.crud2.toggleSelection()
              setTimeout(() => {
                this.loading = false;
                this.butLoading = false;
                this.dialogble = ''
              }, 500)
            });
          }
        });
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      handlePay(row) {
        this.parentId = row.id;
        const column = this.findObject(this.option.column, "parentId");
        column.value = row.id;
        column.addDisabled = true;
        this.$refs.crud.rowAdd();
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(row) {
        this.loading = true;
        this.myQuery.isSearchAll = 0;
        getDetail(row.consignConfigId, this.myQuery.isSearchAll == 1).then(res => {
          this.data2 = res.data.data;
          this.dialogble = row.consignConfigId;
          setTimeout(() => {
            this.loading = false;
          }, 400)
        });
        // if (["edit", "view"].includes(type)) {
        // }
        // done();
      },
      allPay(row) {
        this.loading = true;
        let ids = this.consignList.map(ele => ele.id);
        let orderConsignIds = this.consignList;
        // let orderConsignIds = this.consignList.map(ele => ele.orderConsignId)
        let payType = '1'
        // return
        payMoneyApi(row.consignConfigId, ids, payType, orderConsignIds).then(res => {
          if(res.data.code != 200) this.$message.error(res.data.msg)
          else this.$message.success(res.data.msg)
          setTimeout(() => {
            this.loading = false;
            this.butLoading = false;
            this.dialogble = ''
          }, 500)
          this.onLoad(this.page);
        });
      },
      searchChange2(params, done) {
        this.loading = true;
        getDetail(this.dialogble, this.myQuery.isSearchAll == 1).then(res => {
          this.data2 = res.data.data;
          setTimeout(() => {
            this.loading = false;
          }, 400)
        });
        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;
        getPlatformList(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.data = data;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
  /* .avue-data-display{
    height: 100%;
  } */
  .avue-data-display .item {
    margin: 0px;
  }
  .avue-data-display .count {
    margin: 0px;
    font-size: 22px;
  }
  .avue-data-display .title {
    font-size: 14px;
    margin-bottom: 0px;
  }
</style>
