<template>
  <section class="AppAccountQxn">
    <ai-list>
      <ai-title slot="title" title="账号管理" isShowBottomBorder>
        <template #rightBtn>
          <el-button size="small" type="primary" icon="iconfont iconUpdate_Files" @click="syncDept">同步部门</el-button>
        </template>
      </ai-title>
      <template #left>
        <ai-address-book-menu :instance="instance" @select="handleSelect"/>
      </template>
      <template #content>
        <ai-title :title="tableTitle"/>
        <ai-search-bar>
          <template #left>
            <el-button type="primary" :disabled="!ids.toString()" @click="batchAllot">功能分配</el-button>
            <el-button size="small" icon="iconfont iconUpdate_Files" @click="syncMembers">同步成员</el-button>
          </template>
          <template #right>
            <el-input size="small" placeholder="搜索姓名、手机号" v-model="search.name" clearable
                      v-throttle="() => {page.current = 1, getTableData()}"/>
          </template>
        </ai-search-bar>
        <ai-table :tableData="tableData" :total="page.total" :current.sync="page.current" :size.sync="page.size"
                  @getList="getTableData" :col-configs="colConfigs" :dict="dict"
                  @selection-change="v=>ids=v.filter(e=>e.sysUserId).map(e=>e.sysUserId)">
          <el-table-column slot="name" label="姓名" width="180px">
            <el-row type="flex" align="middle" slot-scope="{row}">
              <el-image class="avatar" :src="row.avatar" :preview-src-list="[row.avatar]">
                <el-image slot="error" src="https://cdn.cunwuyun.cn/dvcp/h5/defaultAvatar.png" alt=""/>
              </el-image>
              <div>{{ row.name }}</div>
            </el-row>
          </el-table-column>
          <el-table-column slot="options" align="center" label="操作" fixed="right" width="160px">
            <el-row type="flex" justify="center" align="middle" slot-scope="{row}">
              <el-button v-if="$permissions('admin_sysuser_distribute')&&!!row.sysUserId"
                         type="text" @click="appAllot(row)">功能分配
              </el-button>
            </el-row>
          </el-table-column>
        </ai-table>
      </template>
    </ai-list>
    <!--功能分配-->
    <ai-dialog title="功能分配" :visible.sync="dialog" width="800px" @open="initDialogData" @onConfirm="updateAccount">
      <el-form ref="updateAccountForm" :model="dialogForm" :rules="rules" size="small"
               label-width="120px">
        <el-form-item required label="角色" prop="roleId">
          <el-select size="small" placeholder="请选择角色" :value="dialogForm.roleId" filterable
                     v-model="dialogForm.roleId" clearable>
            <el-option v-for="(op,i) in accountRoles" :key="i" :label="op.name" :value="op.id"/>
          </el-select>
        </el-form-item>
        <el-form-item required label="主部门" prop="wxMainDepartmentId">
          <ai-select v-model="dialogForm.wxMainDepartmentId" placeholder="请选择主部门" :instance="instance" action="/app/wxcp/wxdepartment/listAll"
                     :prop="{label:'fullName'}"/>
        </el-form-item>
        <el-form-item label="行政地区" prop="areaId">
          <ai-area-select v-model="dialogForm.areaId" always-show :instance="instance"
                          clearable @fullname="v=>dialogForm.areaFullName=v"
                          @name="v=>dialogForm.areaName=v"
                          :disabledLevel="disabledLevel"/>
        </el-form-item>
        <el-form-item label="党组织" prop="organizationId" v-if="user.info.organizationId">
          <el-cascader :options="partyOrgOps" v-model="dialogForm.organizationId"
                       :props="cascaderProps" :show-all-levels="false" clearable/>
        </el-form-item>
        <!--        <el-form-item label="职务" prop="position">-->
        <!--          <el-input placeholder="请输入职务" v-model="dialogForm.position" clearable/>-->
        <!--        </el-form-item>-->
      </el-form>
    </ai-dialog>
  </section>
</template>

<script>
import {mapState} from "vuex";

export default {
  name: "AppAccountQxn",
  label: "账号管理(村微版)",
  props: {
    instance: Function,
    dict: Object,
    permissions: Function
  },
  computed: {
    ...mapState(['user']),
    cascaderProps() {
      return {
        value: 'id',
        checkStrictly: true,
        emitPath: false
      }
    },
    partyOrgOps() {
      let initData = JSON.parse(JSON.stringify(this.optionsParty)),
          ops = initData.filter(e => !e.parentId)
      ops.map(e => this.addChild(e, initData))
      return ops
    },
    colConfigs() {
      return [
        {type: 'selection', align: 'center'},
        {label: "姓名", slot: "name"},
        {label: "职务", prop: "position", align: 'center', width: "120px"},
        {label: "部门", prop: "departmentNames", align: 'center', width: "120px"},
        {label: "联系方式", prop: "mobile", align: 'center', width: "120px"},
        {label: "账号状态", prop: "status", dict: "wxUserStatus", width: "120px"},
        {label: "账号角色", prop: "roleName", width: "120px", align: '120px'},
        {label: "地区", prop: "areaName", width: "120px"},
        {label: "党组织", prop: "organizationName", align: 'center', width: "120px"},
        {slot: "options"}
      ]
    },
    tableTitle() {
      return this.condition ? this.condition + `(${this.page.total})` : '请选择组织或标签'
    },
    rules() {
      return {
        name: [{required: true, message: "请填写姓名"}],
        // organizationId: [{required: true, message: "请选择党组织"}],
        // unitId: [{required: true, message: "请选择单位"}],
        areaId: [{required: true, message: '请选择地区', trigger: 'change'}],
        roleId: [{required: true, message: "请选择角色"}],
        phone: [{required: true, message: "请输入手机号码"}],
        wxMainDepartmentId: [{required: true, message: "请选择主部门"}],
      }
    },
    disabledLevel() {
      return this.user.info.areaList?.length || 0
    }
  },
  data() {
    return {
      condition: "",
      accountRoles: [],
      page: {current: 1, size: 10, total: 0},
      dialog: false,
      dialogForm: {},
      optionsParty: [],
      tableData: [],
      search: {name: ""},
      ids: [],
      lock: false
    }
  },
  methods: {
    getTableData() {
      this.instance.post("/app/wxcp/wxuser/list", null, {
        params: {...this.page, ...this.search}
      }).then(res => {
        if (res?.data) {
          this.tableData = res.data?.records
          this.page.total = res.data.total
        }
      })
    },
    handleSelect(v) {
      if (v.type == 0) {
        //选择部门
        let {id: departmentId, name} = v
        this.condition = name
        this.search = {departmentId}
      } else if (v.type == 1) {
        //选择标签
        let {id: tagIds, tagname: name} = v
        this.condition = name
        this.search = {tagIds}
      }
      this.page.current = 1
      this.getTableData()
    },
    initDialogData() {
      //用于优化初始化数据
      this.getAccountRoles()
      this.searchSysAll()
    },
    getAccountRoles() {
      this.accountRoles.length == 0 && this.instance.post("/admin/role-acc/list-all").then(res => {
        if (res?.data) {
          this.accountRoles = res.data
        }
      })
    },
    batchAllot() {
      this.dialog = true
      this.dialogForm = {areaId: this.user.info.areaId, sysUserIds: this.ids}
    },
    appAllot(row) {
      this.dialog = true
      this.dialogForm = JSON.parse(JSON.stringify({
        ...row,
        sysUserIds: [row.sysUserId],
        areaId: row.areaId || this.user.info.areaId
      }));
    },
    // 获取党组织树形
    searchSysAll() {
      if (this.user.info.organizationId && this.optionsParty.length == 0) {
        this.instance.post('/app/partyOrganization/queryPartyOrganizationServiceList').then((res) => {
          if (res?.data) {
            res.data = res.data.map(a => {
              return {...a, label: a.name}
            });
            this.optionsParty = res.data.filter(e => !e.parentId)
            this.optionsParty.map(t => this.addChild(t, res.data));
          }
        })
      }
    },
    // 修改
    updateAccount() {
      this.$refs.updateAccountForm.validate(v => {
        if (v) {
          if (this.lock) return this.$message.error("请勿多次提交!")
          this.lock = true
          this.instance.post("/app/wxcp/wxuser/empower", this.dialogForm).then(res => {
            this.lock = false
            if (res?.code == 0) {
              this.dialog = false;
              this.$message.success("修改成功")
              this.getTableData();
            } else {
              this.$message.error(res?.msg)
            }
          }).catch(() => {
            this.lock = false
          })
        }
      })
    },
    syncMembers() {
      const {departmentId = 1} = this.search;
      let loading = this.$loading({
        text: "正在同步成员...",
        spinner: 'el-icon-loading',
        background: "rgba(0,0,0,.8)"
      })
      this.instance.post(`/app/wxcp/wxdepartment/syncUser`, null, {
        timeout: 1000000,
        params: {departmentId}
      }).then(res => {
        if (res?.code == 0) {
          this.$message.success('同步成功')
          this.getList()
        }
      }).finally(() => loading.close())
    },
    syncDept() {
      let loading = this.$loading({
        text: "正在同步部门...",
        spinner: 'el-icon-loading',
        background: "rgba(0,0,0,.8)"
      })
      this.instance.post(`/app/wxcp/wxdepartment/syncDepart`).then(res => {
        if (res?.code == 0) {
          this.$message.success('同步成功')
          this.getTree()
        }
      }).finally(() => loading.close())
    }
  },
  created() {
    this.dict.load('wxUserStatus')
  }
}
</script>

<style lang="scss" scoped>
.AppAccountQxn {
  height: 100%;

  :deep( .avatar ) {
    width: 40px;
    height: 40px;
    margin-right: 10px;
  }

  :deep( .ai-list__content--left ) {
    margin-right: 2px;
  }

  :deep( .el-form ) {
    .el-cascader {
      width: 100%;
    }
  }
}
</style>
