<!--
 * @Descripttion:
 * @version:
 * @Author: kBank
 * @Date: 2022-10-24 15:45:01
-->
<template>
  <div class="page">
    <topBar
      v-if="topList.length > 0"
      :top-list="topList"
      :moren="moren"
    />
    <div class="main">
      <el-form
        ref="select"
        :model="select"
        style="padding:0 10px 0 10px;background: #fff"
        label-width="auto"
      >
        <el-row :gutter="20">
          <!-- 一层 -->
          <el-col :span="4">
            <el-form-item :label="'结算期数'">
              <el-input
                v-model="select.memberSettlePeriodId"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item :label="'币种展示'">
              <el-select
                v-model="select.pkCurrency"
                clearable
                placeholder=""
              >
                <el-option
                  v-for="item in acList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="'结算日期'">
              <el-date-picker
                v-model="creationTime"
                value-format="yyyy-MM-dd"
                type="daterange"
                format="yyyy-MM-dd"
                :range-separator="'至'"
                :start-placeholder="'开始日期'"
                :end-placeholder="'结束日期'"
                @change="changeTime"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item :label="'隶属体系'">
              <el-cascader
                v-model="select.pkBdVertexStred"
                :options="verList"
                :props="props"
                collapse-tags
                clearable
                @change="getPkBdVertexStr"
              />
            </el-form-item>
          </el-col>
          <el-col
            :span="4"
          >
            <el-button
              type="primary"
              size="small"
              class="my_search"
              @click="getDataList"
            > {{ '搜索' }}</el-button>
            <el-button
              class="my_reset"
              @click="reset"
            > {{ '重置' }}</el-button>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col>
            <el-form-item :label="'隶属体系'"
                          style="margin-top: -5px">
              <el-checkbox-group v-model="select.pkVertex">
                <el-checkbox v-for="item in verList"
                             :key="item.pkId"
                             :label="item.pkId">
                  {{item.vertexName}}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row> -->
        <!-- <el-row style="margin-top: 0px">
          <el-col>
            <el-form-item :label="'隶属团队'"
                          style="margin-top: -15px">
              <el-checkbox-group v-model="select.pkMemberTeam">
                <el-checkbox v-for="item in memberList"
                             :key="item.pkId"
                             :label="item.pkId">
                  {{item.teamName}}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
      <div class="maintop">
        <div class="mainbtn">
          <el-button
            v-has-buttons="['performanceTotalExport']"
            size="small"
            class="thebtn2"
            @click="handleExport"
          > {{ '导出' }}</el-button>
        </div>
        <!-- <div>
          <el-dropdown :hide-on-click="false">
            <span class="el-dropdown-link kuang">
              {{'筛选字段'}}<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="item in menuList"
                                :key="item.id">
                <el-checkbox v-model="item.checked"
                             @change="getMenu($event,item.id)">{{ item.text }}</el-checkbox></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div> -->
      </div>
      <div class="maintable">
        <div class="itemTrading">
          <el-table
            ref="mainTable"
            v-loading="loading"
            :data="tableData"
            height="730px"
            style="width: 100%"
            :header-cell-style="{ background: '#EEEEEE' }"
            :row-class-name="tableRowClassName"
            :summary-method="getSummaries"
            show-summary
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              width="55"
            />
            <!-- <el-table-column align="center"
                             prop="numberPeriods"
                             width="150"
                             v-if="dataList[0].key"
                             :label="'结算期数'">
            </el-table-column> -->
            <el-table-column
              v-if="allTxt.settleDate"
              align="center"
              prop="settleDate"
              width="150"
              :label="'结算时间'"
            />
            <el-table-column
              v-if="allTxt.registerAmount"
              align="center"
              prop="registerAmount"
              :formatter="stateFormat"
              width="160"
              :label="'注册金额'+`(￥)`"
            />

            <!-- <el-table-column
              v-if="allTxt.registerAmountLocality"
              align="center"
              prop="registerAmountLocality"
              :formatter="stateFormat"
              width="160"
              :label="'注册金额'+`(${isLocalSymbol()})`"
            /> -->
            <el-table-column
              v-if="allTxt.registerPv"
              align="center"
              prop="registerPv"
              :formatter="stateFormat"
              width="160"
              :label="'注册业绩'+`(￥)`"
            />

            <!-- <el-table-column
              v-if="allTxt.registerPvLocality"
              align="center"
              prop="registerPvLocality"
              :formatter="stateFormat"
              width="160"
              :label="'注册业绩'+`(${isLocalSymbol()})`"
            /> -->
            <el-table-column
              v-if="allTxt.upgradeAmount"
              align="center"
              prop="upgradeAmount"
              :formatter="stateFormat"
              width="160"
              :label="'升级金额'+`(￥)`"
            />

            <!-- <el-table-column
              v-if="allTxt.upgradeAmountLocality"
              align="center"
              prop="upgradeAmountLocality"
              :formatter="stateFormat"
              width="160"
              :label="'升级金额'+`(${isLocalSymbol()})`"
            /> -->

            <el-table-column
              v-if="allTxt.upgradePv"
              align="center"
              prop="upgradePv"
              :formatter="stateFormat"
              width="160"
              :label="'升级业绩'+`(￥)`"
            />

            <!-- <el-table-column
              v-if="allTxt.upgradePvLocality"
              align="center"
              prop="upgradePvLocality"
              :formatter="stateFormat"
              width="160"
              :label="'升级业绩'+`(${isLocalSymbol()})`"
            /> -->

            <el-table-column
              v-if="allTxt.firstPurchaseAmount"
              align="center"
              prop="firstPurchaseAmount"
              :formatter="stateFormat"
              width="160"
              :label="'首购金额'+`(￥)`"
            />

            <!-- <el-table-column
              v-if="allTxt.firstPurchaseAmountLocality"
              align="center"
              prop="firstPurchaseAmountLocality"
              :formatter="stateFormat"
              width="160"
              :label="'首购金额'+`(${isLocalSymbol()})`"
            /> -->
            <el-table-column
              v-if="allTxt.firstPurchasePv"
              align="center"
              prop="firstPurchasePv"
              :formatter="stateFormat"
              width="160"
              :label="'首购业绩'+`(￥)`"
            />

            <!-- <el-table-column
              v-if="allTxt.firstPurchasePvLocality"
              align="center"
              prop="firstPurchasePvLocality"
              :formatter="stateFormat"
              width="160"
              :label="'首购业绩'+`(${isLocalSymbol()})`"
            /> -->

            <!-- <el-table-column
              v-if="allTxt.tripartiteAmountLocality&&getUser.user.pkCountry==1"
              align="center"
              prop="tripartiteAmountLocality"
              :formatter="stateFormat"
              width="160"
              :label="'三方' +'金额'+`(${isLocalSymbol()})`"
            /> -->

            <!-- <el-table-column
              v-if="allTxt.tripartitePvLocality&&getUser.user.pkCountry==1"
              align="center"
              prop="tripartitePvLocality"
              :formatter="stateFormat"
              width="160"
              :label="'三方' +'业绩'+`(${isLocalSymbol()})`"
            /> -->

            <!-- <el-table-column
              v-if="allTxt.fansAmountLocality&&getUser.user.pkCountry==1"
              align="center"
              prop="fansAmountLocality"
              :formatter="stateFormat"
              width="150"
              :label="'海粉金额'+`(${isLocalSymbol()})`"
            /> -->

            <!-- <el-table-column
              v-if="allTxt.hiFunPvLocality&&getUser.user.pkCountry==1"
              align="center"
              prop="hiFunPvLocality"
              :formatter="stateFormat"
              width="150"
              :label="'海粉业绩'+`(${isLocalSymbol()})`"
            /> -->
            <el-table-column
              v-if="allTxt.repurchaseAmount"
              align="center"
              prop="repurchaseAmount"
              :formatter="stateFormat"
              width="160"
              :label="'复购金额'+`(￥)`"
            />

            <!-- <el-table-column
              v-if="allTxt.repurchaseAmountLocality"
              align="center"
              prop="repurchaseAmountLocality"
              :formatter="stateFormat"
              width="150"
              :label="'复购金额'+`(${isLocalSymbol()})`"
            /> -->
            <el-table-column
              v-if="allTxt.repurchasePv"
              align="center"
              prop="repurchasePv"
              :formatter="stateFormat"
              width="150"
              :label="'复购业绩'+'(￥)'"
            />

            <!-- <el-table-column
              v-if="allTxt.repurchasePvLocality"
              align="center"
              prop="repurchasePvLocality"
              :formatter="stateFormat"
              width="150"
              :label="'复购业绩'+`(${isLocalSymbol()})`"
            /> -->
            <el-table-column
              v-if="allTxt.amountTotal"
              align="center"
              prop="amountTotal"
              :formatter="stateFormat"
              width="150"
              :label="'金额总计'+'(￥)'"
            />

            <!-- <el-table-column
              v-if="allTxt.amountTotalLocality"
              align="center"
              prop="amountTotalLocality"
              :formatter="stateFormat"
              width="150"
              :label="'金额总计'+`(${isLocalSymbol()})`"
            /> -->
            <el-table-column
              v-if="allTxt.pvTotal"
              align="center"
              prop="pvTotal"
              :formatter="stateFormat"
              width="150"
              :label="'业绩汇总'+'(￥)'"
            />

            <!-- <el-table-column
              v-if="allTxt.pvTotalLocality"
              align="center"
              prop="pvTotalLocality"
              :formatter="stateFormat"
              width="150"
              :label="'业绩汇总'+`(${isLocalSymbol()})`"
            /> -->

          </el-table>
        </div>

      </div>
    </div>
  </div>
</template>

<script>
import topBar from '@/components/topBar'
import * as api from '@/api/settle.js'
import { classifyUpdate, classifySave } from '@/api/product'
import { isLocalSymbol, stateFormat } from '@/utils/numberToCurrency'
import { getRoleMenu } from '@/api/notice'
import { toThousandthAndKeepDecimal } from '@/utils/numberToCurrency'
import { mapGetters } from 'vuex'

export default {
  name: 'Bzpz',
  components: {
    topBar
  },
  filters: {
    isAgree(val) {
      if (!val) {
        return '允许'
      } else {
        return '禁止'
      }
    }
  },
  data() {
    return {
      typeList: [
        {
          value: 0,
          label: '前台'
        },
        {
          value: 1,
          label: '后台'
        }
      ],
      digList: [
        {
          value: 0,
          label: '允许'
        },
        {
          value: 1,
          label: '禁止'
        }
      ],
      creationTime: [],
      creationTime1: [],
      select: {
        pkVertex: [],
        pkMemberTeam: []
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50
      },
      addOrEdit: '',
      total: 0,
      dialogVisible: false,
      tableData: [],
      loading: false,
      moren: '/settlementCenter/performanceTotal',
      topList: [
        {
          name: '业绩汇总',
          path: '/settlementCenter/performanceTotal'
        }
      ],
      form: {
        name: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入规格类型', trigger: 'blur' }
        ]
      },
      acList: [],
      verList: [],
      memberList: [],
      flag: false,
      allTxt: {},
      props: {
        multiple: true,
        expandTrigger: 'hover',
        value: 'pkId',
        label: 'vertexName',
        children: 'childList'
      }
    }
  },
  computed: {
    ...mapGetters(['getUser'])
  },
  mounted() {
    // 获取下拉
    this.getData()
    var s1 = this.getStartTime()
    var s2 = this.getEndTime()
    this.select.startDate = s1
    this.select.endDate = s2
    this.creationTime = [s1, s2]
    console.log('%c [ this.creationTime ]-587', 'font-size:13px; background:#433918; color:#877d5c;', this.creationTime)
    // 获取列表
    this.getDataList()
    this.getUserRole()
  },
  methods: {
    getPkBdVertexStr(e) {
      console.log('%c [ e ]-616', 'font-size:13px; background:#d9149a; color:#ff58de;', e)
      const arr = e.map((item) => item[1])
      const pkBdVertexStr = arr.join(',')
      this.$set(this.select, 'pkBdVertexStr', pkBdVertexStr)
    },
    getStartTime() {
      const date = new Date()
      // console.error(date.getDate()==1?date.getMonth():date.getMonth() + 1)
      const year = date.getFullYear() // 得到当前年份
      let month = date.getDate() === 1 ? date.getMonth() : date.getMonth() + 1 // 得到当前月份（0-11月份，+1是当前月份）
      date.setDate(1) // 将当前时间的日期设置成第一天
      month = month >= 10 ? month : '0' + month // 补零
      let day = date.getDate() // 得到当前天数，实际是本月第一天，因为前面setDate(1) 设置过了
      day = day >= 10 ? day : '0' + day // 补零
      return year + '-' + month + '-' + day
    },
    getEndTime() {
      var date = new Date()
      var year = date.getFullYear() // 年
      let month = date.getDate() === 1 ? date.getMonth() : date.getMonth() + 1 // 得到当前月份（0-11月份，+1是当前月份）
      var day = date.getDate()
      const day1 = date.getDate()
      // 给一位数的数据前面加 “0”
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (day >= 0 && day <= 9) {
        day = '0' + day
      }
      if (day1 == 1) {
        var date2 = new Date()
        var year2 = date2.getFullYear()
        var month2 = date2.getMonth()
        var dates = new Date(year2, month2, 0).getDate()
        day = dates
      }
      return year + '-' + month + '-' + day
    },
    isLocalSymbol,
    toThousandthAndKeepDecimal,
    getUserRole() {
      getRoleMenu('performanceTotal').then((res) => {
        const obj = {}
        res.data.forEach((item) => {
          obj[item] = 1
        })
        this.allTxt = obj
        this.$nextTick(() => {
          this.$refs.mainTable.doLayout()
        })
      })
    },
    stateFormat,
    reset() {
      this.creationTime = ''
      this.select = {
        pkVertex: [],
        pkMemberTeam: []
      }
    },
    getData() {
      api.accountList().then((res) => {
        this.acList = res.data
      })
      // api.vertexList().then((res) => {
      //   this.verList = res.data
      // })
      api.vertexChild().then((res) => {
        this.verList = res.data
      })
      api.memberTeam().then((res) => {
        this.memberList = res.rows
      })
    },
    changeTime(val) {
      if (val) {
        this.select.startDate = val[0]
        this.select.endDate = val[1]
      }
    },
    changeTime1(val) {
      this.select.startEffectDate = val[0]
      this.select.endEffectDate = val[1]
    },
    // 点击修改
    toFixed(id) {
      this.addOrEdit = false
      this.dialogVisible = true
      this.$router.push({
        path: 'noticeList/details',
        query: {
          pkId: id
        }
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出所有数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((_) => {
        this.download(
          'member/manage/member-structure/export',
          Object.assign({}, this.queryParams, this.select),
          `业绩汇总-${new Date().getTime()}.xlsx`
        )
      })
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = ''
          return
        }
        if (index === 1) {
          sums[index] = '小计'
          return
        }
        const values = data.map((item) => Number(item[column.property]))
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          // sums[index] += ' 元';
        } else {
          sums[index] = ''
        }
      })
      // sums
      const arr = ['', '小计']

      sums.forEach((item) => {
        if (typeof item === 'number') {
          arr.push(toThousandthAndKeepDecimal(item))
        }
      })
      this.$nextTick(() => {
        this.$refs.mainTable.doLayout()
      })
      return arr
    },
    // 删除
    handleDelete(id) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.classifyDel(id).then((res) => {
          this.getDataList()
        })
      })
    },
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = ''
          if (this.addOrEdit == true) {
            url = classifySave
          } else {
            url = classifyUpdate
          }
          url(this.form).then((res) => {
            if (res.code == 200) {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.dialogVisible = false
              // 充值数据
              this.$refs[formName].resetFields()
              // 获取列表
              this.getDataList()
            }
          })
        } else {
          return false
        }
      })
    },
    handleClose() {
      this.dialogVisible = false
      this.$refs['form'].clearValidate()
      this.$refs['form'].resetFields()
    },
    openDig() {
      this.$router.push({
        path: 'noticeList/details'
      })
    },
    getDataList() {
      this.loading = true
      if (this.creationTime == '' || this.creationTime == null) {
        this.select.startDate = ''
        this.select.endDate = ''
      }
      api
        .memberStructure(Object.assign({}, this.queryParams, this.select))
        .then((res) => {
          this.loading = false
          this.tableData = res.data
          // this.total = res.total
        })
    },
    handleSelectionChange(val) {},
    // /** 导出按钮操作 */
    // handleExport() {
    //   const queryParams = this.queryParams
    //   this.$confirm( '是否确认导出所有数据项?', '警告', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning',
    //   })
    //     .then(function () {
    //       return api.exportClassIfy(queryParams)
    //     })
    //     .then((response) => {
    //       this.download(response)
    //     })
    // },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 == 1) {
        return 'warning-row'
      } else if (rowIndex % 2 == 0) {
        return 'success-row'
      }
      return ''
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .el-range-editor.el-input__inner {
  width: 100%;
}
::v-deep .el-button {
  //height: 32px;
  //line-height: 32px;
  padding: 8px 20px;
}
::v-deep .el-date-editor .el-range__close-icon {
  margin-top: -10px;
}
::v-deep .el-date-editor .el-range-separator {
  margin-top: -10px;
}
::v-deep .el-date-editor .el-range__icon {
  margin-top: -10px;
}
::v-deep .el-cascader input {
  height: 32px !important;;
  //line-height: 28px;
}
::v-deep .el-form-item {
  margin-bottom: 0;
}
::v-deep .el-form-item__label {
  color: #333;
  font-weight: inherit;
}

::v-deep .el-table .warning-row {
  background: #f9f9f9;
}

::v-deep .el-table .success-row {
  background: #ffffff;
}
::v-deep .el-table thead {
  color: #000000;
}
::v-deep .el-select {
  width: 100%;
}
.uploadIcon ::v-deep .el-upload--picture-card {
  display: none !important; /* 上传按钮隐藏 */
}
.page {
  padding: 20px;
  background: #f9f9f9;
  font-size: 14px;
  .main {
    background: #f9f9f9;
    //border-radius: 8px;
    //box-shadow: 0px 2px 20px 0px rgba(238, 238, 238, 0.5);
    overflow: hidden;
    display: flex;
    flex-direction: column;
    .maintop {
      display: flex;
      //padding: 10px 20px;
      //padding: 10px 0;
      justify-content: space-between;
      align-items: center;
      .mainbtn {
        .thebtn1 {
          background: #3181e5;
          color: #ffffff;
        }
        .thebtn2 {
          background: #ffad41;
          color: #ffffff;
        }
      }
      .maintitle {
        font-size: 10px;
        font-family: MicrosoftYaHei;
        color: #999999;
      }
    }
    .maintable{
      flex: 1;
      overflow-y: auto;
    }
  }
  .tem {
    display: flex;
    align-items: center;
    justify-content: center;
    img {
      width: 28px;
      height: 20px;
      margin-right: 3px;
    }
  }
  .isRed {
    color: #ed1d25;
  }
  .isGreen {
    color: #1ab62b;
  }
  .bgImg {
    width: 48px;
    height: 48px;
  }
}
.openClose {
  text-align: right;
  margin-right: 10px;
  color: #3181e5;
}
.kuang {
  padding: 5px 20px;
  background: rgba(255, 255, 255, 0);
  border-radius: 4px;
  border: 1px solid #cccccc;
}
.heji {
  margin-top: 10px;
  .dis {
    display: flex;
    justify-content: right;
    padding: 5px 10px;
    font-size: 14px;
    color: #333333;
    :nth-child(1) {
      font-size: 14px;
      font-weight: bold;
      color: #333333;
      margin-right: 20px;
    }
  }
}
</style>
