<template>
  <div class="custom_page">
    <div class="content">
      <!-- 顶部搜索 -->
      <div class="toolbar">
        <!-- 顶部搜索 -->
        <el-form :inline="true" :model="formParams">
          <el-form-item label="客户昵称">
            <el-input v-model="formParams.name" maxlength="20" placeholder="请输入客户昵称" />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="formParams.phone" maxlength="11" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="标签">
            <el-select v-model="formParams.labelId" placeholder="请选择">
              <el-option
                v-for="(item, index) in tipsList" :key="index" :label="item.labelName"
                :value="item.buyerLabelId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="最近消费时间">
            <el-date-picker
              v-model="formParams.dates" type="daterange" range-separator="至" start-placeholder="开始时间"
              end-placeholder="结束时间" value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item>
            <el-form-item label="累计消费金额">
              <el-input v-model="formParams.minMoney" maxlength="9" placeholder="请输入最小值" @input="checkMinMoney" />
            </el-form-item>
            <el-form-item label="-">
              <el-input v-model="formParams.maxMoney" maxlength="9" placeholder="请输入最大值" @input="checkMaxMoney" />
            </el-form-item>
          </el-form-item>
          <el-form-item>
            <el-form-item label="购买次数">
              <el-input
                v-model="formParams.minBuyers" maxlength="9" oninput="value=value.replace(/[^\d]/g,'')"
                placeholder="请输入最小值"
              />
            </el-form-item>
            <el-form-item label="-">
              <el-input
                v-model="formParams.maxBuyers" maxlength="9" oninput="value=value.replace(/[^\d]/g,'')"
                placeholder="请输入最大值"
              />
            </el-form-item>
          </el-form-item>

          <el-form-item label-width="0">
            <el-button type="primary" plain @click="search">查询</el-button>
            <el-button plain @click="clear">重置</el-button>
            <el-button type="primary" plain @click="handleExport">导出</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!--  表格 -->
      <div class="content_table">
        <div class="table">
          <el-table
            :data="tableData" border :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
            style="width: 100%"
          >
            <el-table-column prop="name" label="客户昵称" />
            <el-table-column prop="phone" label="手机号" />
            <el-table-column prop="memberLevelName" label="会员等级" />
            <el-table-column prop="total" label="消费总额" />
            <el-table-column prop="buyers" label="购买次数" />
            <el-table-column prop="credit" label="剩余积分" />
            <el-table-column prop="region" label="区域ID" />
            <el-table-column label="关系">
              <template slot-scope="scope">
                <span v-if="scope.row.roleId == null">无关系</span>
                <span v-if="scope.row.roleId == 1">加盟商</span>
                <span v-if="scope.row.roleId == 2">代理商</span>
              </template>
            </el-table-column>
            <el-table-column prop="time" label="最近消费时间" />
            <el-table-column prop="createTime" label="注册时间" />
            <el-table-column
              :formatter="row => row.registerIp ? row.registerIp : '-'" label="注册IP"
              show-overflow-tooltip
            />
            <el-table-column
              :formatter="row => row.lastLoginIp ? row.lastLoginIp : '-'" prop="time" label="最后登录IP"
              show-overflow-tooltip
            />
            <el-table-column label="操作" fixed="right">
              <template slot-scope="scope">
                <el-button type="text" @click.native.prevent="details(scope.row)">详情</el-button>
                <el-button type="text" @click.native.prevent="setIntegral(scope.row)">设置积分</el-button>
                <el-button type="text" @click.native.prevent="makeTag(scope.row)">打标签</el-button>
                <el-button type="text" size="small" @click.native.prevent="addBlackList(scope.row)">
                  {{ scope.row.ifBlack ? "取消黑名单" : "加入黑名单" }}
                </el-button>
                <el-button type="text" size="small" @click.native.prevent="appointBtn(scope.row)">指定关系</el-button>

              </template>
            </el-table-column>
          </el-table>
          <div class="fenye">
            <el-pagination
              :current-page="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="10"
              layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- *************对话框开始************* -->
    <!-- 打标签 -->
    <el-dialog title="选择标签" :visible.sync="addFormDialog" width="30%" center :close-on-click-modal="false">
      <div>
        <!-- 表单搜索 -->
        <el-form :inline="true" :model="tipsForm" class="demo-form-inline">
          <el-form-item label="标签名称">
            <el-input v-model="tipsForm.labelName" maxlength="20" placeholder="请输入标签名称" />
          </el-form-item>
          <el-form-item>
            <el-button @click="searchTips">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="text" @click="runTips">管理标签</el-button>
          </el-form-item>
        </el-form>
        <!-- 多选 -->
        <el-checkbox-group v-model="checkList">
          <el-checkbox v-for="(item, index) in tipsList" :key="index" class="checkBoxStyle" :label="item.buyerLabelId">
            {{
              item.labelName }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addFormDialog = false">取 消</el-button>
          <el-button type="primary" @click="saveTips">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      title="修改会员积分" :visible.sync="editIntegral" width="30%" center
      :close-on-click-modal="false"
      @close="credit = 0"
    >
      <el-form label-width="100px">
        <el-form-item label="修改积分">
          <el-radio-group v-model="updateWay" @change="changeWayRadio">
            <el-radio :label="true">增加</el-radio>
            <el-radio :label="false">减少</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="积分">
          <el-input-number v-if="updateWay" v-model="credit" :min="0" :max="9999999" />
          <el-input-number v-if="!updateWay" v-model="credit" :max="0" />
        </el-form-item>
        <el-form-item style="margin-top:-18px;color:#999999">
          <span>提示 : 在原有积分上增加或减少</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editIntegral = false">取 消</el-button>
          <el-button type="primary" @click="saveIntegral">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!--  指定关系 -->
    <el-dialog
      title="选择关系" :visible.sync="appointDialog" width="40%" center
      :close-on-click-modal="false"
      @close="appintClose"
    >
      <template #footer>
        <span class="dialog-footer">
          <el-form ref="ruleForm" label-width="120px" :model="appintForm" :rules="rules">
            <div class="lable-list">
              <div class="lable-item">
                <el-form-item label="加盟商名称:" prop="name">
                  <el-input v-model="appintForm.name" placeholder="请输入名称"></el-input>
                </el-form-item>
              </div>
              <div class="lable-item">
                <el-form-item label="加盟商电话:" prop="phone">
                  <el-input v-model="appintForm.phone" placeholder="请输入电话"></el-input>
                </el-form-item>
              </div>
            </div>
            <div class="lable-list">
              <div class="lable-item">
                <el-form-item label="请选择区域:" prop="area">
                  <!-- <el-cascader  :props="{checkStrictly: true}"  ref="cascaderRef" @change="handleCascaderChange"></el-cascader> -->
                  <el-cascader ref="cascaderRef" :props="areaData" @change="handleCascaderChange"></el-cascader>
                </el-form-item>
              </div>
              <div class="lable-item">
                <el-form-item label="详细地址:" prop="address">
                  <el-input v-model="appintForm.address" placeholder="请输入详细地址"></el-input>
                </el-form-item>
              </div>
            </div>
            <div class="lable-list">
              <div class="lable-item">
                <el-form-item label="店长名称:" prop="chargePersonName">
                  <el-input v-model="appintForm.chargePersonName" placeholder="请输入店长名称"></el-input>
                </el-form-item>
              </div>
              <div v-if="appintForm.type == 5" class="lable-item">
                <el-form-item label="选择小区:" prop="communityId">
                  <el-select v-model="communityId" placeholder="请选择">
                    <el-option
                      v-for="item in communityList" :key="item.id" :label="item.communityName"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
            </div>
            <el-form-item label="选择指定关系:" prop="type">
              <template>
                <el-radio v-model="appintForm.type" :label="1">团长</el-radio>
                <el-radio v-model="appintForm.type" :label="2">合伙人</el-radio>
                <el-radio v-model="appintForm.type" :label="3">加盟商</el-radio>
                <el-radio v-model="appintForm.type" :label="4">区代理</el-radio>
                <el-radio v-model="appintForm.type" :label="5">小区</el-radio>
              </template>
            </el-form-item>
          </el-form>
          <el-button @click="appintCan">取消</el-button>
          <el-button type="primary" @click="appintDetermine">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户详情 -->
    <UserDetails ref="UserDetails" @success="getList" />
  </div>
</template>

<script>
import {
  customerMageGetAll,
  getLabels,
  customerSaveUserLabel,
  customerBlacklist,
  updateBuyerCredit,
  exportBuyerUser,
  appointUserRelationship
} from '@/api/customerMage'
import { getProvinceList, getChildAreaList, getCommunityList } from '@/api/address'
import UserDetails from './components/UserDetails'

export default {
  name: 'MemberList',
  components: {
    UserDetails
  },
  data() {
    return {
      showMore: false,
      formParams: {
        name: '', // 用户昵称
        phone: '', // 手机号
        labelId: '', // 标签id
        dates: [], // 最近消费时间日期数组
        minMoney: '', // 累计消费金额最小值
        maxMoney: '', // 累计消费金额最大值
        minBuyers: '', // 购买次数最小值
        maxBuyers: '', // 购买次数最大值
        startTime: '', // 申请开始时间
        endTime: '', // 申请结束时间
        page: 1,
        pageSize: 10
      },
      tipsForm: {
        labelName: ''
      },
      date: [],
      total: 1,
      tableData: [],
      currentPage: 1,
      dialog: {},
      tipsList: [],
      checkList: [],
      addFormDialog: false,
      editIntegral: false,
      buyerUserId: '', // 用户id
      credit: '', // 积分值 扣减积分则传负数
      updateWay: true, // 修改积分单选绑定
      appointDialog: false, // 指定关系的弹出框
      areaData: {
        lazy: true,
        checkStrictly: true,
        label: 'name',
        value: 'id',
        lazyLoad(node, resolve) {
          const { level, value } = node
          if (level === 0) {
            getProvinceList().then((res) => {
              resolve(res.data)
              console.log(res)
            })
          } else if (level != 0) {
            getChildAreaList(value).then((res) => {
              resolve(res.data.map((item) => {
                item.leaf = level === 3
                return item
              }))
            })
          }
        }
      },
      //
      cityId: '',
      appintForm: {
        userId: null,
        area: null,
        type: '',
        name: '',
        phone: '',
        address: '',
        chargePersonName: ''
      },

      // 小区数据
      communityList: [],
      //  小区的id
      communityId: '',

      //  指定关系正则校验
      rules: {
        name: [
          { required: true, message: '请填写加盟商名称', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '请填写加盟商电话', trigger: 'change' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'change' }
        ],
        area: [
          { required: true, message: '请选择区域', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请填写详细地址', trigger: 'change' }
        ],
        chargePersonName: [
          { required: true, message: '请输入店长名称', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择你需要指定的关系', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getSelect({ labelName: '' })
  },
  methods: {
    /**
		 * 导出
		 */

    async handleExport() {
      this.$message({
        message: '数据导出中，请勿重复操作！',
        type: 'success'
      })
      console.log(this.formParams, 'this.formParams')
      const res = await exportBuyerUser(this.formParams)
      if (!res) {
        return
      }
      const blob = new Blob([ res ], { type: 'application/vnd.ms-excel' })
      const fileName = '用户列表.xls'
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a')
        elink.download = fileName
        elink.href = URL.createObjectURL(blob)
        elink.style.display = 'none'
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    },
    handleSizeChange(val) {
      this.formParams.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.formParams.page = val
      this.getList()
    },
    // 查询
    search() {
      this.total = 1
      this.formParams.page = 1
      this.getList()
    },
    // 查询标签
    searchTips() {
      console.log(this.tipsForm)
      this.getSelect({ labelName: this.tipsForm.labelName })
    },
    changeWayRadio(val) {
      this.updateWay = val
    },
    // 设置积分（更新积分）
    setIntegral(row) {
      this.editIntegral = true
      this.buyerUserId = row.buyerUserId
    },
    async saveIntegral() {
      if (this.credit === '' || this.credit === undefined) {
        return this.$message('积分不能为空！')
      } else if (this.credit === 0) {
        this.editIntegral = false
      } else {
        const res = await updateBuyerCredit({
          buyerUserId: this.buyerUserId,
          credit: this.credit
        })
        if (res.code === '') {
          this.getList()
          this.editIntegral = false
          this.$message.success('修改积分成功')
        }
      }
    },
    // 打标签
    async saveTips(row) {
      console.log(this.checkList)
      const res = await customerSaveUserLabel({
        buyerUserId: this.buyerUserId,
        buyerLabelIds: this.checkList
      })
      if (res.code === '') {
        this.$message({
          message: '成功',
          type: 'success'
        })
        this.checkList = []
        this.tipsForm.labelName = ''
        this.addFormDialog = false
      }
    },
    //  指定关系
    appointBtn(row) {
      this.appintForm.userId = row.buyerUserId
      this.appointDialog = true
    },
    // 获取省数据
    async handleCascaderChange() {
      const checkedNode = this.$refs.cascaderRef.getCheckedNodes()
      const nodeData = checkedNode[0].data
      const res = await getChildAreaList(nodeData.id)
      if (res.data.length == 0) {
        const res2 = await getCommunityList({ cityId: nodeData.id })
        this.communityList = res2.data
      }
      console.log(res)

      this.appintForm.area = nodeData.id
    },
    //  指定关系取消
    appintCan() {
      this.appointDialog = false
    },
    //  指定关系确认
    async appintDetermine() {
      //  先进行校验
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.appintForm.type == 5 && this.communityId == '') {
            this.$message.error('请选择小区，如没有小区的话，是该区域没有小区，请选择有区域的小区')
            return
          }
          if (this.appintForm.type == 5 && this.communityId != '') {
            this.appintForm.communityId = this.communityId
          }
          const res = await appointUserRelationship(this.appintForm)
          if (res.code == '') {
            this.$message({
              message: '添加成功',
              type: res.message
            })
            this.appointDialog = false
            this.search()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })

      // if (this.appintForm.region == null && this.appintForm.isType != '3') {
      //   this.$message.error("请选择区域");
      //   return
      // }
      // let res = await appointRelationship(this.appintForm);
      // if (res.code == "") {
      //   this.$message.success("指定关系成功")
      //   this.appointDialog = false
      // }
      //  重新获取数据
      this.getList()
    },
    //  弹窗关闭 把数据重置
    appintClose() {
      this.appintForm = {
        userId: null,
        area: null,
        type: '',
        name: '',
        phone: '',
        address: '',
        chargePersonName: '',
        communityId: ''
      }
      this.communityId = ''
      this.communityList = []
      this.$refs.cascaderRef.inputValue = ''
      this.$refs.ruleForm.resetFields()
    },
    // 加入黑名单
    addBlackList(row) {
      //  "ifBlack": "是否加入黑名单 1-是 0-否"
      console.log(row.ifBlack)
      this.$confirm(
        `${row.ifBlack
          ? '确认是否取消黑名单'
          : '加入黑名单后，对方将无法登录商城'
        }`,
        `${row.ifBlack ? '取消黑名单' : '加入黑名单'}`,
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          if (!row.ifBlack) {
            customerBlacklist({
              buyerUserId: row.buyerUserId,
              ifBlack: 1
            }).then((res) => {
              if (res.code === '') {
                this.$message({
                  type: 'success',
                  message: '成功!'
                })
                this.getList()
              }
            })
          } else {
            customerBlacklist({
              buyerUserId: row.buyerUserId,
              ifBlack: 0
            }).then((res) => {
              if (res.code === '') {
                this.$message({
                  type: 'success',
                  message: '成功!'
                })
                this.getList()
              }
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    // 跳转标签页面
    runTips() {
      this.$router.push({
        path: '/member/tips'
      })
    },
    // 清除
    clear() {
      this.formParams = {
        name: '', // 用户昵称
        phone: '', // 手机号
        labelId: '', // 标签id
        dates: [], // 最近消费时间日期数组
        minMoney: '', // 累计消费金额最小值
        maxMoney: '', // 累计消费金额最大值
        minBuyers: '', // 购买次数最小值
        maxBuyers: '', // 购买次数最大值
        page: 1,
        pageSize: 10
      }
      this.getList()
    },
    // 打标签
    makeTag(row) {
      this.checkList = row.labelIds
      this.tipsForm.labelName = ''
      this.addFormDialog = true
      this.buyerUserId = row.buyerUserId
    },
    details(row) {
      // this.$router.push({
      //   name: 'customerDetails',
      //   params: { buyerUserId: row.buyerUserId, orderFormid: row.orderFormid }
      // })
      this.$refs.UserDetails && this.$refs.UserDetails.handleOpen(row)
    },
    // 初始化查询所有数据
    async getList() {
      const res = await customerMageGetAll(this.formParams)
      this.tableData = res.data.list
      this.total = res.data.total
    },
    // 初始化查询所有标签
    async getSelect(name) {
      const res = await getLabels(name)
      this.tipsList = res.data
    },
    reset() {
      this.getList()
    },
    checkMinMoney(e) {
      this.formParams.minMoney = e.match(/^\d*(\.?\d{0,2})/g)[0] || null
    },
    checkMaxMoney(e) {
      this.formParams.maxMoney = e.match(/^\d*(\.?\d{0,2})/g)[0] || null
    }
  }
}
</script>

<style lang='scss' scoped>
@import url("../../../styles/elDialog.scss");

.custom_page {
	padding: 20px;
}

.checkBoxStyle {
	margin-bottom: 20px;
}

.lable-list {
	display: flex;
	align-items: center;

	.lable-item {
		// flex: 1;
		width: 50%;
	}
}

::v-deep .el-cascader {
	width: 100%
}
</style>
