<template>
  <div class="app-container">
    <span>返利互转单</span>
    <el-divider></el-divider>
    <!-- 筛选条件 -->
    <div>
      <el-form ref="searchForm" :model="searchForm" label-width="100px" size="mini" label-position="left">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="返利互转单号" prop="">
              <el-input disabled placeholder="系统自动生成"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="单据日期" prop="theTime">
              <el-date-picker
                disabled
                class="dateStyle"
                placeholder="系统自动生成"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="制单人" prop="">
              <el-input v-model="searchForm.nickName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="经销商编号" prop="">
              <el-input disabled v-model="searchForm.customerNumber"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="经销商名称" prop="">
              <el-input disabled v-model="searchForm.customerName"></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="备注信息" prop="">
              <el-input placeholder="请输入"></el-input>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
    </div>
    <!-- 列表 -->
    <div class="mymain-container">
      <div class="table">
        <el-table
          v-loading="listLoading"
          :data="dataList"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
          stripe
        >
          <el-table-column label="序号" type="index" align="left" width="100" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" label="经销商编码" prop="customerNumber" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              <div v-if="scope.$index == 0">
                <div v-if="isCustomer">{{ searchForm.customerNumber }}</div>
                <div v-else>
                  <el-select
                    size="mini"
                    class="dateStyle"
                    @change="changeCustomerNumber($event, 0)"
                    filterable
                    v-model.trim="scope.row.customerNumber"
                    placeholder="请选择"
                  >
                    <el-option v-for="item in customerData" :key="item.id" :label="item.number" :value="item.number">
                    </el-option>
                  </el-select>
                </div>
              </div>
              <div v-if="scope.$index == 1">
                <div v-if="isCustomer">{{ scope.row.customerNumber }}</div>
                <div v-else>
                  <el-select
                    size="mini"
                    class="dateStyle"
                    @change="changeCustomerNumber($event, 1)"
                    filterable
                    v-model.trim="scope.row.customerNumber"
                    placeholder="请选择"
                  >
                    <el-option v-for="item in customerData" :key="item.id" :label="item.number" :value="item.number">
                    </el-option>
                  </el-select>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="经销商名称" prop="customerName" min-width="260" show-overflow-tooltip>
            <template slot-scope="scope">
              <div v-if="scope.$index == 0">{{ searchForm.customerName }}</div>
              <el-select
                size="mini"
                class="dateStyle"
                @change="changeCustomerFn1($event, scope.$index, scope.row)"
                v-if="scope.$index == 1"
                filterable
                v-model="scope.row.customerId"
                placeholder="请选择"
              >
                <el-option v-for="item in customerData" :key="item.id" :label="item.name" :value="item.id"> </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="left" label="返利类型" prop="name" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-select
                size="mini"
                filterable
                v-model="scope.row.name"
                placeholder="请选择"
                @click.native="changeCustomerFn(scope.row, scope.$index)"
              >
                <el-option
                  v-for="item in scope.row.typeList"
                  :key="item.customerWalletId"
                  :label="item.name"
                  :value="item.customerWalletId"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="left" label="返利金额" prop="" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-input size="mini" type="number" @mousewheel.native.prevent v-model="scope.row.money"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="left" label="折让金额" prop="" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              <div v-if="scope.$index == 0"></div>
              <el-input
                v-if="scope.$index == 1"
                size="mini"
                type="number"
                @mousewheel.native.prevent
                v-model="scope.row.allowanceAmount"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column align="left" label="备注" prop="" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-input size="mini" v-model="scope.row.bz"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 按钮 -->
    <div class="btn-group clearfix">
      <div class="fl">
        <el-button type="primary" size="mini" @click="preservationFn">保存</el-button>

        <el-button type="primary" size="mini" @click="resetFn">重置</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  getUserInfo,
  getWalletCustomerList,
  getTransferAdd,
  getTransferSubmit,
  getCustomerGroupList
} from '@/api/finance/change_apply'
import ret from 'bluebird/js/release/util'

export default {
  data() {
    return {
      listLoading: false, // 列表加载loading
      dataList: [
        {
          customerNumber: '',
          customerId: '',
          name: '',
          money: '',
          bz: ''
        },
        {
          customerNumber: '',
          customerId: '',
          name: '',
          money: '',
          bz: '',
          allowanceAmount: ''
        }
      ],
      searchForm: {
        customerId: '',
        customerName: '',
        nickName: '',
        customerNumber: ''
      },
      customerData: [], //经销商数据
      typeList: [], //返利类型数据
      // rules: {
      //   theTime: [
      //     {
      //       required: true,
      //       message: "请选择日期",
      //       trigger: "change",
      //     },
      //   ],
      // },
      isCustomer: JSON.parse(localStorage.getItem('supply_user')).isCustomer
    }
  },
  computed: {
    ...mapGetters(['userid'])
  },
  created() {
    this.getUserInfoFn()
    this.getCustomerData()
  },
  methods: {
    //选择经销商名称事件
    async changeCustomerFn1(v, index, value) {
      // value.customerWalletId = "";
      // console.log(v);

      const res = await getWalletCustomerList({
        customerId: v,
        type: 'REBATE'
      })
      // console.log(res, 7878);
      const res2 = this.customerData.filter(i => i.id == v)
      // console.log(res2, 8888);

      this.$set(this.dataList[1], 'customerNumber', res2[0].number)
      // this.$set(this.dataList[index], "customerName", res2[0].name);

      // this.$set(this.dataList[index], "walletList", res.data);
    },
    // func(arr, target) {
    //   var obj = {};
    //   for (var i = 0; i < arr.length; i++) {
    //     var item = arr[i].money;
    //     if (obj[item] === undefined) {
    //       var x = target - item;
    //       obj[x] = i;
    //     } else {
    //       return [obj[item], i];
    //     }
    //   }
    //   return null;
    // },
    changeCustomerNumber(e, index) {
      if (!index) {
        const customerData = this.customerData.find(k => {
          return k.number === e
        })
        this.searchForm.customerName = customerData.name
        this.$set(this.dataList[index], 'customerId', customerData.id)
      } else {
        const id = this.customerData.find(k => {
          return k.number === e
        }).id
        this.$set(this.dataList[index], 'customerId', id)
      }
      this.$set(this.dataList[index], 'customerNumber', e)
    },
    resetFn() {
      this.searchForm.theTime = null
      this.dataList.forEach(v => {
        v.money = ''
        v.bz = ''
        v.name = ''
      })
      this.searchForm.customerName = ''
      this.dataList[0].customerId = ''
      this.dataList[0].customerNumber = ''
      this.dataList[0].customerName = ''
      this.dataList[0].allowanceAmount = ''
      this.dataList[1].customerId = ''
      this.dataList[1].customerNumber = ''
      this.dataList[1].allowanceAmount = ''
    },

    // //返利类型数据
    async changeCustomerFn(v, index) {
      console.log(v)
      if (v.customerId == '') {
        return
      }

      v.name = ''
      let res = await getWalletCustomerList({
        customerId: v.customerId,
        type: 'REBATE'
      })

      this.$set(this.dataList[index], 'typeList', res.data)

      // if (index == 1) {
      //   let aa = res.data.filter(
      //     (v) => v.customerWalletId != this.dataList[0].name
      //   );
      //   this.$set(this.dataList[index], "typeList", aa);
      // } else {
      //   this.$set(this.dataList[index], "typeList", res.data);
      // }
    },

    // async typeFn(row) {
    //   console.log(row);
    //   let res = await getWalletCustomerList({
    //     customerId: row.customerId,
    //     type: "REBATE",
    //   });
    //   this.typeList = res.data;
    // },

    //查询同个集团的经销商数据
    async getCustomerData() {
      const res = await getCustomerGroupList()
      // console.log(res, 123214);
      this.customerData = res.data
    },

    //保存
    async preservationFn() {
      // let receiverWalletRebateId;
      // let initiatorWalletRebateId;
      // let initiatorRemark;
      // let receiverRemark;
      // let amount;

      await this.$refs.searchForm.validate()

      let aaa = this.dataList.find(v => {
        if (v.money == '') {
          this.$message.error('请输入返利金额')
          return v
        }
        if (v.customerId == '') {
          this.$message.error('请选择经销商')
          return v
        }
        if (v.name == '') {
          this.$message.error('请选择返利类型')
          return v
        }
      })

      if (aaa != undefined) {
        return
      }
      if (this.dataList[0].money > 0) {
        this.$message.error('转出金额必须为负数')
        return
      }
      if (this.dataList[1].money < 0 && this.dataList[1].allowanceAmount < 0) {
        this.$message.error('转入金额必须为正数')
        return
      }
      if (
        Number(-this.dataList[0].money) !=
        Number(this.dataList[1].money) + Number(this.dataList[1].allowanceAmount)
      ) {
        this.$message.error('转入转出金额不等,请重新输入')
        return
      }

      // if (this.dataList[0].money > 0) {
      //   receiverWalletRebateId = this.dataList[0].name;
      //   initiatorWalletRebateId = this.dataList[1].name;
      //   initiatorRemark = this.dataList[1].bz;
      //   receiverRemark = this.dataList[0].bz;
      //   amount = this.dataList[0].money;
      // } else {
      //   receiverWalletRebateId = this.dataList[1].name;
      //   initiatorWalletRebateId = this.dataList[0].name;
      //   initiatorRemark = this.dataList[0].bz;
      //   receiverRemark = this.dataList[1].bz;
      //   amount = this.dataList[1].money;
      // }

      let params = {
        amount: this.dataList[1].money,
        initiatorAmount: this.dataList[0].money,
        initiatorWalletRebateId: this.dataList[0].name,
        receiverWalletRebateId: this.dataList[1].name,
        allowanceAmount: this.dataList[1].allowanceAmount,
        initiatorRemark: this.dataList[0].bz,
        receiverRemark: this.dataList[1].bz
      }

      await getTransferAdd(params)
      this.resetFn()
      this.$router.push('/finance/change_list')
      // this.$router.push('/rebate/change_list')

      this.$message.success('申请成功')
    },
    async getUserInfoFn() {
      const res = await getUserInfo({ adminUserId: this.userid })
      this.searchForm.customerNumber = res.data.customerNumber
      this.dataList[0].customerId = res.data.customerId
      this.searchForm.customerName = res.data.customerName
      this.searchForm.customerNumber = res.data.customerNumber
      this.searchForm.nickName = res.data.nickName
      // const res2 = await getWalletCustomerList({
      //   customerId: res.data.customerId,
      //   type: "REBATE",
      // });
      // console.log(res2, 5555);
      // res2.data.forEach((v) => {
      //   v.money = "";
      //   v.bz = "";
      // });
      // this.dataList = res2.data;
      // console.log(this.dataList);
    }
  }
}
</script>

<style lang="scss" scoped>
.dateStyle {
  width: 100%;
}
</style>
