<template>
  <div class="wrap">
    <!-- 左边的组织 -->
    <div class="side">
      <div class="m-b-20">
        <h6 class="p-title">或然城市合伙人</h6>
        <el-radio-group v-model="type" @change="typeChange">
          <div class="m-b-20">
            <el-radio :label="1">城市合伙人</el-radio>
          </div>
          <div>
            <el-radio :label="2">未加入团队的合伙人</el-radio>
          </div>
        </el-radio-group>
      </div>
      <el-divider></el-divider>
      <div>
        <div class="flex-between">
          <h6 class="p-title" style="margin-bottom: 0">组织架构</h6>
          <el-button type="text" @click="addOrg" v-auth="'/parner:账号管理:添加分类'">添加分类</el-button>
        </div>

        <div style="height: 504px; max-height: 504px; overflow: auto">
          <el-tree :data="orgList" default-expand-all ref="orgTree" node-key="id" highlight-current
            :expand-on-click-node="false" @node-click="handleNodeClick"
            :props="{ children: 'children', label: 'partnerClassificationName', isLeaf: 'leaf' }">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span class="org-name">{{ node.label }}</span>
              <span>
                <!-- isTeam 0: 分类，1: 团队 -->
                <el-button v-auth="'/parner:账号管理:添加分类'" v-if="!data.isTeam" type="text"
                  icon="el-icon-circle-plus-outline" @click="() => addOrg(node, data)">
                </el-button>
                <el-button v-auth="'/parner:账号管理:编辑分类'" type="text" icon="el-icon-edit-outline"
                  @click="() => editOrg(node, data)">
                </el-button>
                <el-button v-auth="'/parner:账号管理:删除分类'" type="text" icon="el-icon-delete"
                  @click="() => delOrg(node, data)">
                </el-button>
              </span>
            </span>
          </el-tree>
        </div>
      </div>

      <el-dialog :title="typeForm.id ? '编辑' : '新增' + '分类'" :visible.sync="orgVisible" :close-on-click-modal="false"
        width="50%" @close="closeType">
        <el-form v-if="orgVisible" ref="typeForm" :model="typeForm" :rules="orgRules" label-width="100px">
          <el-form-item label="分类名称" prop="partnerClassificationName">
            <el-input v-model.trim="typeForm.partnerClassificationName" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="上级部门">
            <span v-if="typeForm.parentName">{{ typeForm.parentName }}</span>
            <el-cascader v-else :options="orgListDia" v-model="cascaderValue" :props="cascaderProps" clearable
              style="width: 100%">
            </el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeOrg">取 消</el-button>
          <el-button type="primary" @click="orgSubmit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <!-- 右边的员工 -->
    <div class="right">
      <h6 class="p-title">筛选</h6>
      <div class="tool">
        <ul class="filter">
          <li>
            <el-input style="width: 250px;" placeholder="请输入员工姓名/手机号" prefix-icon="el-icon-search" v-model="keyWord"
              clearable></el-input>
          </li>
        </ul>
        <div>
          <el-button type="primary" @click="add(0)" v-auth="'/parner:账号管理:添加城市合伙人'">添加城市合伙人</el-button>
        </div>
      </div>

      <el-table :data="listData" class="table" ref="table" header-align="center"
        @selection-change="handleSelectionChange" row-key="id">
        <el-table-column type="selection" width="55" align="center" :reserve-selection="true"></el-table-column>
        <el-table-column type="index" width="60" label="序号" align="center"></el-table-column>
        <el-table-column prop="userName" label="姓名" align="center" min-width="100"></el-table-column>
        <el-table-column prop="account" label="账号" align="center" min-width="100"></el-table-column>
        <el-table-column prop="phone" label="手机号" align="center" min-width="120"></el-table-column>
        <el-table-column prop="invitationAccount" label="邀请人" align="center" min-width="120"></el-table-column>
        <el-table-column prop="partnerClassificationName" label="团队名称" align="center" min-width="120"
          show-overflow-tooltip></el-table-column>
        <template v-if="!type">
          <el-table-column prop="provinceName" label="省份" align="center" min-width="80"></el-table-column>
          <el-table-column prop="cityName" label="城市" align="center" min-width="80"></el-table-column>
          <el-table-column prop="roleName" label="授权角色" align="center" min-width="120"
            show-overflow-tooltip></el-table-column>
          <el-table-column prop="phone" label="费率" align="center" min-width="120">
            <template slot-scope="scope">
              <p v-if="scope.row.annualTeamFee">团队年费{{ scope.row.annualTeamFee }}w</p>
              <p v-if="scope.row.annualMarketingFee">市场服务年费{{ scope.row.annualMarketingFee }}%</p>
            </template>
          </el-table-column>
        </template>
        <el-table-column prop="loginNumber" label="登录次数" align="center" width="120"></el-table-column>
        <el-table-column prop="lastLoginTime" label="上次登录时间" align="center" width="120"></el-table-column>
        <el-table-column label="操作" align="center" width="300">
          <template slot-scope="scope">
            <el-button v-if="!type" type="text" v-auth="'/parner:账号管理:重置密码'" @click="edit(scope.row)">编辑</el-button>
            <el-button type="text" v-auth="'/parner:账号管理:重置密码'" @click="resetPassword(scope.row)">重置密码</el-button>
            <el-button v-if="type" type="text" v-auth="'/parner:账号管理:删除合伙人'" @click="del(scope.row)">删除</el-button>
            <el-button v-else-if="scope.row.isTeam == 1" type="text" v-auth="'/parner:账号管理:转让超管'"
              @click="transfer(scope.row)">转让超管</el-button>
            <el-button v-if="scope.row.isTeam == 0" type="text" v-auth="'/parner:账号管理:移除'"
              @click="remove(scope.row)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background @current-change="currentChange" :current-page="page" layout="total, prev, pager, next"
          :total="total"></el-pagination>
      </div>

      <el-dialog title="添加城市合伙人" :visible.sync="parnerVisible" width="580px" custom-class="add-dia"
        :close-on-click-modal="false" @close="closeAdd">
        <p class="tips">链接/二维码失效时间：{{ expireTime }}</p>
        <p class="title">城市合伙人 <em>邀请链接</em></p>
        <p class="des">加盟商、合作伙伴可以通过这个链接加入 <em>城市合伙人计划</em></p>
        <div class="link-wrap">
          <div class="link">{{ link }}</div>
          <el-button type="primary" size="small" @click="copy">复制链接</el-button>
        </div>
        <p class="title">城市合伙人 <em>邀请二维码</em></p>
        <p class="des">加盟商、合作伙伴可以通过这个二维码加入 <em>城市合伙人计划</em></p>
        <img width="250" :src="qrcode" alt="">
      </el-dialog>

      <el-dialog title="转让管理员" :visible.sync="transferVisible" width="350px" custom-class="transfer-dia"
        :close-on-click-modal="false">
        <div style="text-align: center">
          <el-button type="primary" @click="showChoose">转给团队成员</el-button>
          <el-button @click="add(1)">邀请外部人员</el-button>
        </div>
      </el-dialog>

      <el-dialog title="请选择要转让的团队成员" :visible.sync="chooseVisible" width="300px" custom-class="choose-dia"
        :close-on-click-modal="false">
        <ul class="member-list">
          <li v-for="(item, i) in members" :key="i">
            <div class="info">
              <img src="@/assets/img/avatar.png" alt="">
              <span class="name">{{ item.userName }}</span>
            </div>
            <el-radio v-model="choosePartnerId" :label="item.partnerId"
              :disabled="curRow.accountId === item.accountId"></el-radio>
          </li>
        </ul>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="chooseVisible = false">取 消</el-button>
          <el-button size="small" type="primary" @click="chooseSubmit">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="编辑合伙人" :visible.sync="editVisible" width="400px" class="dialog" :close-on-click-modal="false">
        <el-form ref="form" :model="form" :rules="rules" label-width="60px" style='margin-right: 0;'>
          <el-form-item prop="userName" label="姓名">
            <el-input v-model.trim="form.userName" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item prop="roleList" label="角色">
            <el-select class="w-100" v-model="form.roleList" multiple>
              <template v-for="item in roleList">
                <!-- 不显示超管 -->
                <el-option :key="item.id" :label="item.roleName" :value="item.id">
                </el-option>
              </template>
            </el-select>
          </el-form-item>
          <el-form-item prop="provinceId" label="省份">
            <el-select style="width: 100%" v-model="form.provinceId" placeholder="请选择省份" @change="getCity">
              <el-option v-for="(item, index) in provinces" :key="index" :label="item.provinceName"
                :value="item.provinceId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="cityId" label="城市">
            <el-select style="width: 100%" v-model="form.cityId" placeholder="请选择城市"
              :disabled="form.provinceId ? false : true">
              <el-option v-for="(item, index) in cities" :key="index" :label="item.cityName"
                :value="item.cityId"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import util from "@/libs/util";
import Setting from "@/setting";
import OrgTree from "@/components/org-tree/src/tree";
import clipboard from '@/libs/clipboard'
import axios from 'axios'
export default {
  components: { OrgTree },
  data () {
    return {
      accountId: this.$store.state.accountId,
      userName: this.$store.state.userName,
      type: 1,
      orgList: [],
      orgListDia: [],
      orgVisible: false, // 员工组织架对话框
      typeForm: {
        id: '',
        partnerClassificationName: ''
      },
      cascaderValue: [], // 上级部门
      cascaderProps: {
        checkStrictly: true,
        label: "partnerClassificationName",
        value: "id"
      },
      treeVisible: true,
      treeNode: {},
      treeResolve: [],
      isDetail: false,
      keyWord: '',
      form: {
        userName: '',
        provinceId: '',
        cityId: '',
        roleList: []
      },
      rules: {
        userName: [
          { required: true, message: "请输入姓名", trigger: "blur" }
        ],
        provinceId: [
          { required: true, message: '请选择省份', trigger: "change" }
        ],
        cityId: [
          { required: true, message: '请选择城市', trigger: "change" }
        ],
        roleList: [
          { required: true, message: '请选择角色', trigger: "change" }
        ],
      },
      listData: [],
      page: 1,
      pageSize: 10,
      total: 0,
      multipleSelection: [],

      orgRules: {
        partnerClassificationName: [
          { required: true, message: "请输入部门名称", trigger: "blur" }
        ]
      },
      parnerVisible: false,
      casProps: {
        multiple: true,
        checkStrictly: true,
        label: 'partnerClassificationName',
        value: 'id',
        isLeaf: 'leaf'
      },
      link: '',
      qrcode: '',
      expireTime: '',
      curTeamId: '',
      submiting: false, // 新增编辑防抖标识
      setKey: '',
      transferVisible: false,
      chooseVisible: false,
      members: [],
      choosePartnerId: '',
      curRow: '',
      provinces: [],
      cities: [],
      editVisible: false
    };
  },
  watch: {
    keyWord: function (val) {
      clearTimeout(this.searchTimer);
      this.searchTimer = setTimeout(this.initData, 500);
    }
  },
  mounted () {
    this.getOrg()
    this.getProvince()
    this.getRole()
  },
  methods: {
    // 获取组织
    async getOrg () {
      const res = await this.$post(this.api.listParner)
      const list = res.treeList
      // 没有子级，删除children属性
      const handleLeaf = (list, ids) => {
        list.map(e => {
          e.ids = ids ? [...ids, e.id] : [e.id]
          if (e.children.length) {
            if (e.isTeam) {
              delete e.children
            } else {
              handleLeaf(e.children, e.ids)
            }
          } else {
            delete e.children
          }
        })
      }
      handleLeaf(list)
      this.orgList = list
      // 如果刚编辑完，则选中刚编辑的分类
      this.setKey && this.$nextTick(() => {
        this.$refs.orgTree.setCurrentKey(this.setKey)
      })
      this.getList()
    },
    // 类型回调
    typeChange () {
      this.$refs.orgTree.setCurrentKey(null)
      this.curTeamId = ''
      this.initData()
    },
    // 添加部门
    addOrg (node, data) {
      const list = JSON.parse(JSON.stringify(this.orgList))
      this.handleOrg(list)
      this.orgListDia = list
      this.typeForm = {
        id: '',
        parentId: data ? data.id : 1,
        level: data ? data.level + 1 : 1,
        parentName: data ? data.partnerClassificationName : '',
        partnerClassificationName: ''
      }
      this.cascaderValue = []
      this.orgVisible = true
    },
    // 编辑部门
    editOrg (node, data) {
      const list = JSON.parse(JSON.stringify(this.orgList))
      this.handleOrg(list)
      this.orgListDia = list
      this.typeForm = {
        id: data.id,
        partnerClassificationName: data.partnerClassificationName,
        isTeam: data.isTeam
      }
      this.orgVisible = true
      const { ids } = data
      ids.splice(ids.length - 1, 1)
      this.cascaderValue = ids
    },
    // 关闭分类弹框
    closeType () {
      this.typeForm = {
        id: '',
        partnerClassificationName: ''
      }
    },
    // 处理更换部门的禁选
    handleOrg (list) {
      for (const i in list) {
        const e = list[i]
        // 如果是团队，则禁选
        if (e.isTeam) {
          e.disabled = true
        } else {
          this.handleOrg(e.children)
        }
      }
    },
    // 删除部门
    delOrg (node, data) {
      this.$confirm(data.isTeam ? '确定删除该城市合伙人？删除后，该团队同步解散，且不可恢复！' : '确定要删除吗？', "提示", {
        type: "warning"
      }).then(() => {
        this.$post(`${this.api.deleteParner}?id=${data.id}`).then(res => {
          util.successMsg("删除成功")
          this.getOrg()
        }).catch(res => { })
      }).catch(() => { })
    },
    // 提交组织架构新增/编辑
    orgSubmit () {
      this.$refs.typeForm.validate((valid) => {
        if (valid) {
          const form = this.typeForm
          const cas = this.cascaderValue
          const len = cas.length
          if (cas && len) {
            this.typeForm.parentId = cas[len - 1]
            this.typeForm.level = len + 1
          }
          if (!form.id) {
            // 添加
            this.$post(this.api.saveParner, form).then(res => {
              util.successMsg("新增成功！")
              this.closeOrg()
            }).catch(err => { })
          } else {
            // 编辑
            this.$post(this.api.updateParner, form).then(res => {
              util.successMsg("编辑成功！")
              this.setKey = form.id
              this.closeOrg()
            }).catch(err => { })
          }
        }
      });
    },
    // 获得点击层级里的第一个城市合伙人id
    getTeamId (list) {
      for (const i in list) {
        const e = list[i]
        if (e.isTeam && !this.curTeamId) {
          this.curTeamId = e.id
          break
        } else {
          this.getTeamId(e.children)
        }
      }
    },
    // 点击树节点查询列表数据
    handleNodeClick (data) {
      this.type = ''
      this.curTeamId = ''
      if (data.isTeam) {
        this.curTeamId = data.id
      } else {
        // this.getTeamId(data.children)
      }
      if (!this.curTeamId) this.curTeamId = data.id
      this.initData()
      this.$refs.table.clearSelection()
    },
    // 关闭组织新增编辑弹框
    closeOrg () {
      this.orgVisible = false
      this.cascaderValue = []
      this.getOrg()
    },
    // 查询全部
    getAll () {
      this.curTeamId = ''
      this.getList()
    },
    // 员工列表
    getList () {
      this.$post(this.api[this.type ? 'partnerAccountMergeList' : 'partnerAccountList'], {
        type: this.type || 1,
        partnerClassificationId: this.curTeamId,
        keyWord: this.keyWord,
        pageNum: this.page,
        pageSize: this.pageSize
      }).then(({ pageList }) => {
        pageList.records.forEach((e, i) => {
          e.id = i
        })
        this.listData = pageList.records
        console.log("🚀 ~ file: staff.vue:479 ~ getList ~ this.listData:", this.listData)

        this.total = pageList.total
      }).catch(err => { })
    },
    // 切换页码
    currentChange (val) {
      this.page = val
      this.getList()
    },
    handleSelectionChange (val) { // 多选
      this.multipleSelection = val
    },
    initData () {
      this.$refs.table.clearSelection()
      this.page = 1
      this.getList()
    },
    // 获取省份
    getProvince () {
      this.$get(this.api.queryProvince).then(res => {
        this.provinces = res.list
      }).catch(res => { })
    },
    // 获取城市
    getCity (val) {
      this.$get(this.api.queryCity, {
        provinceId: this.form.provinceId
      }).then(res => {
        this.cities = res.list
        if (val) this.form.cityId = ''
      }).catch(res => { })
    },
    // 删除
    del (row) {
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning"
      }).then(() => {
        this.$post(`${this.api.delPartnerAccount}?accountId=${row.accountId}`).then(res => {
          util.successMsg("删除成功")
          this.getList()
        }).catch(res => { })
      }).catch(() => { })
    },
    // 移除
    remove (row) {
      this.$confirm("确定要移除吗？", "提示", {
        type: "warning"
      }).then(() => {
        this.$get(this.api.partnerRemoval, {
          partnerId: row.partnerId,
          teamId: row.partnerClassificationId,
        }).then(res => {
          util.successMsg("移除成功")
          this.getList()
        }).catch(res => { })
      }).catch(() => { })
    },
    // 转让超管
    transfer (row) {
      this.curRow = row
      this.transferVisible = true
    },
    getRole () {
      // platformId 合伙人为4，具体看setting.js；port: pc端为0、小程序端为1
      this.$get(`${this.api.roleList}?page=1&size=10000&platformId=4&port=1&name=`).then(res => {
        this.roleList = res.rolePage.records;
      }).catch(res => { });
    },
    // 编辑
    edit (row) {
      if (!row.provinceId) row.provinceId = ''
      if (!row.cityId) row.cityId = ''
      row.roleList = row.roleId.split(',').map(e => +e)
      this.editVisible = true
      this.form = JSON.parse(JSON.stringify(row))
      row.cityId && this.getCity()
    },
    // 编辑提交
    submitEdit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.submiting) return false
          this.submiting = true
          const form = JSON.parse(JSON.stringify(this.form))
          form.classificationId = form.partnerClassificationId
          this.$post(this.api.editProvinceCity, form).then(res => {
            this.getList()
            util.successMsg("编辑成功！")
            this.editVisible = false
            setTimeout(() => {
              this.submiting = false
            }, 2000)
          }).catch(res => {
            setTimeout(() => {
              this.submiting = false
            }, 2000)
          })
        }
      })
    },
    // 重置密码
    resetPassword (row) {
      const newPwd = Setting.initialPassword
      this.$confirm(`重置后的密码为：${newPwd}，确定重置？`, "提示", { type: "warning" }).then(() => {
        this.$get(`${this.api.resetPwd}?userId=${row.userId}&newPwd=${newPwd}`).then(res => {
          util.successMsg("重置成功")
        }).catch(res => { })
      }).catch(() => { })
    },
    // 显示选择成员
    showChoose () {
      this.chooseVisible = true
      this.$post(this.api.partnerAccountList, {
        type: 1,
        partnerClassificationId: this.curRow.partnerClassificationId,
        keyWord: '',
        pageNum: 1,
        pageSize: 10000
      }).then(({ pageList }) => {
        this.members = pageList.records
      }).catch(err => { })
    },
    // 选择成员提交
    chooseSubmit () {
      const { curRow } = this
      const id = this.choosePartnerId
      const member = this.members.find(e => e.partnerId === id) // 获取选择的成员
      if (member) {
        this.$post(this.api.transferTeam, {
          adminPartnerId: curRow.partnerId,
          adminTeamId: curRow.partnerClassificationId,
          memberName: member.userName,
          memberPartnerId: member.partnerId,
          memberTeamId: member.partnerClassificationId
        }).then(({ pageList }) => {
          this.chooseVisible = false
          this.transferVisible = false
          this.getOrg()
        }).catch(err => { })
      } else {
        util.warningMsg('请选择成员！')
      }
    },
    // 添加
    add (transfer) {
      // 非转让超管，不能在团队下加团队
      if (!transfer) {
        const curNode = this.$refs.orgTree.getCurrentNode()
        if (curNode && curNode.isTeam) return util.warningMsg('请选择分类添加城市合伙人！')
      }
      const { curRow } = this
      const accountId = transfer ? curRow.accountId : this.accountId
      // 获取邀请码
      this.$post(`${this.api[transfer ? 'generateTransferCode' : 'generateInvitationCode']}?accountId=${accountId}`).then(({ expireTime }) => {
        const date = new Date(Date.now() + expireTime * 1000) // 返回的秒，要*1000
        this.expireTime = `${date.getFullYear()}-${util.preZero(date.getMonth() + 1)}-${util.preZero(date.getDate())} ${util.preZero(date.getHours())}:${util.preZero(date.getMinutes())}:${util.preZero(date.getMinutes())}`
        this.parnerVisible = true
        const cur = transfer ? curRow.partnerClassificationId : this.$refs.orgTree.getCurrentKey()
        const link = `${location.origin}${Setting.isDev || Setting.isPro ? '' : '/backstage'}/#/join?accountId=${accountId}&id=${cur || ''}${transfer ? '&admin=1&provinceId=' + curRow.provinceId + '&cityId=' + curRow.cityId : '&isTeam=1'}`

        // 生成二维码
        this.link = link
        axios.get(`${this.api.generationQrCode}?url=${encodeURIComponent(link)}`, {
          responseType: 'blob'
        }).then(({ data }) => {
          this.qrcode = window.URL.createObjectURL(data)
        }).catch(res => { })
      }).catch(res => { })
    },
    closeAdd () {
      this.initData()
    },
    // 复制链接
    copy (e) {
      clipboard(this.link, e, '链接已复制！')
    }
  }
};
</script>

<style lang="scss" scoped>
.m-b-20 {
  margin-bottom: 20px;
}

.org-name {
  margin-right: 20px;
}

.w-100 {
  width: 100%;
}

.wrap {
  display: flex;
  padding: 0 24px;

  .side {
    width: 300px;
    padding: 24px 10px 24px 0;
    margin-right: 24px;
    border-right: 1px solid rgba(0, 0, 0, 0.06);
  }

  .right {
    width: calc(100% - 324px);
    padding: 24px 0;
  }
}

.add-dia {
  .tips {
    font-size: 12px;
    color: #f00;
  }

  .title {
    margin: 10px 0;
    font-size: 14px;

    em {
      font-style: normal;
    }
  }

  .des {
    font-size: 13px;
    color: #7a7a7a;
  }

  .link-wrap {
    display: flex;
    align-items: center;
    margin: 10px 0 20px;
  }

  .link {
    padding: 10px;
    margin-right: 15px;
    background-color: #e7f5ff;
    border-radius: 4px;
  }
}

/deep/.choose-dia {
  .member-list {
    li {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
    }

    .info {
      display: inline-flex;
      align-items: center;
    }

    img {
      width: 40px;
      height: 40px;
    }

    .name {
      margin-left: 10px;
    }

    .el-radio__label {
      display: none;
    }
  }
}
</style>