<template>
  <section class="AppAccountXiushan">
    <ai-list>
      <ai-title slot="title" title="账号管理" isShowBottomBorder/>
      <template #content>
        <ai-search-bar>
          <template #left>
            <el-button size="small" type="primary" icon="iconfont iconAdd" @click="accountDialog=true">添加
            </el-button>
            <el-button type="primary" :disabled="!ids.toString()" @click="batchAllot">功能分配</el-button>
          </template>
          <template #right>
            <el-input size="small" placeholder="搜索姓名、手机号" v-model="search.condition" clearable
                      @change="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.map(e=>e.id)">
          <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')"
                         type="text" @click="appAllot(row)">功能分配
              </el-button>
            </el-row>
          </el-table-column>
        </ai-table>
      </template>
    </ai-list>
    <!--添加账号-->
    <ai-dialog title="添加账号" :close-on-click-modal="false" class="editStyle" :visible.sync="accountDialog"
               width="800px" @closed="account={}" @onConfirm="submitAddAcount">
      <el-form ref="addAccountForm" :model="account" :rules="rules" size="small"
               label-width="120px">
        <el-form-item required label="姓名" prop="name">
          <el-input v-model.trim="account.name" placeholder="请输入..." clearable :maxLength="15"/>
        </el-form-item>
        <el-form-item required label="手机号码" prop="phone">
          <el-input v-model.trim="account.phone" placeholder="请输入..." clearable :maxLength="11"/>
        </el-form-item>
        <el-form-item label="行政地区" prop="areaId">
          <ai-area-get v-model="account.areaId" :instance="instance" root="500241000000" showAll/>
        </el-form-item>
      </el-form>
    </ai-dialog>
    <!--功能分配-->
    <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 label="行政地区" prop="areaId">
          <ai-area-get v-model="dialogForm.areaId" :instance="instance" :name.sync="dialogForm.areaName"
                       root="500241000000" showAll/>
        </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: "AppAccountXiushan",
  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: "phone", align: 'center', width: "120px"},
        {label: "账号角色", prop: "roleName", width: "120px", align: '120px'},
        {label: "地区", prop: "areaFullName"},
        {slot: "options"}
      ]
    },
    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: "请输入手机号码"}],
      }
    },
    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: {condition: ""},
      ids: [],
      lock: false,
      accountDialog: false,
      account: {}
    }
  },
  methods: {
    getTableData() {
      this.instance.post("/user/page", 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.id],
        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
          let areaFullName = this.dialogForm.areaName
          this.instance.post("/user/empower", {...this.dialogForm, areaFullName}).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
          })
        }
      })
    },
    //添加账号
    submitAddAcount() {
      this.$refs.addAccountForm.validate(v => {
        if (v) {
          let {account} = this
          this.instance.post("/user/add", account).then(res => {
            if (res?.code == 0) {
              this.$message.success("提交成功!")
              this.accountDialog = false
              this.getTableData();
            }
          })
        }
      })
    }
  },
  created() {
    this.getTableData()
  }
}
</script>

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

  ::v-deep .avatar {
    width: 40px;
    height: 40px;
    margin-right: 10px;
  }
}
</style>
