<template>
    <div class="page_container">
        <div class="bg-breadcrumb">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> 开发管理 </el-breadcrumb-item>
                <el-breadcrumb-item > 系统账号管理 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
         <div class="flex_row">
           <div class="flex_left bgc_white">
             <div class="tree_header">
                 政务机构
             </div>
             <div class="tree_content">
               <div class="search"> 
                 <el-input
                    v-model="filterTree"
                    placeholder="请输入组织名称搜索"
                    :prefix-icon="Search"
                  />
               </div>
               <div class="tree">
                 <el-tree ref="treeRef" 
                          :data="orgData" 
                          :props="defaultProps" 
                          @node-click="handleNodeClick"
                          node-key="id"
                          :highlight-current="true" 
                          :filter-node-method="filterNode" 
                          :default-expand-all="true">
                    <template #default="{ node, data }">
                      <div class="custom_tree_node">
                        <span
                          class="label-text "
                          :title="node.label"
                          >{{ node.label }}
                        </span>
                      </div>
                    </template>
                 </el-tree>
               </div>
             </div>
           </div>
           <div class="flex_right bgc_white">
             <div class="main_container">
               <bg-filter-group @search="changeSearch" v-model="filter.search" placeholder="请输入关键字">
                  <template v-slot:left_action>
                    <div class="apaas_button">
                    <el-button class="register_btn" type="primary" @click="addAccount">
                      <bg-icon style="font-size: 12px; color: #fff; margin-right: 8px" icon="#bg-ic-add"></bg-icon>
                        新建
                    </el-button>
                    <el-button class="register_btn" @click="deleteBatch">
                        批量删除
                    </el-button>
                    <el-button class="register_btn" @click="resetPsd">
                        重置密码
                    </el-button>
                    <span class="header_info">已选择<span style="color: #202531;font-weight: bold">{{selected.length}}</span>项</span>
                    <span class="header_info can_click_text" @click="clearSelected">清空</span>
                  </div>
                  </template>
                </bg-filter-group>
                <div class="table_container apaas_scroll">
                  <bg-table ref="dataTable" :headers="headers" :rows="tableRows" :isIndex="true" :stripe="true" :select="true" @selectAc="selectRows">
                    <template v-slot:business_name="{ row }">
                      <span @click="goDetail(row)" class="can_click_text">
                        {{ row.business_name }}
                      </span>
                    </template>
                    <template v-slot:state="{ row }">
                      <bg-switch @click="stateChange(row)" :labels="['否','是']" :values="[0,1]" v-model="row.state"></bg-switch>
                    </template>
                    <template v-slot:action="{ row }">
                      <bg-table-btn class="can_click_text" @click="editAccount(row.id)">
                        编辑
                      </bg-table-btn>
                      <bg-table-btn class="can_click_text" @click="editPsdAccount(row)">
                        修改密码
                      </bg-table-btn>
                      <bg-table-btn class="can_click_text"  @click="deleteAccount(row)">
                        删除
                      </bg-table-btn>
                    </template>
                  </bg-table>
                  <div class="pagination_box">
                     <bg-pagination
                    :page="filter.page"
                    :size="filter.limit"
                    :total="tableTotal"
                    @change-page="changePage"
                    @change-size="changeSize"
                  >
                  </bg-pagination>
                  </div>
                  
                </div>
                 
              </div>
           </div>
        </div>
        <el-dialog
          v-model="deleteFlag"
          title="删除"
          width="520px"
          :before-close="handleCloseDelete"
        >
          <div class="warning_info">
            <bg-icon style="font-size: 12px; color: #a9b1c7; margin-right: 8px;vertical-align: baseline;" icon="#bg-ic-circle-tips"></bg-icon>
            您正在对 <span class="danger_info">{{selectedName.join('、')}}</span>做删除操作。
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="handleCloseDelete">取消</el-button>
              <el-button type="primary" @click="deleteConfirm">确定</el-button>
            </span>
          </template>
        </el-dialog>
         <el-dialog
          v-model="deleteRowFlag"
          title="删除"
          width="520px"
          :before-close="handleCloseRowDelete"
        >
          <div class="warning_info">
            <bg-icon style="font-size: 12px; color: #a9b1c7; margin-right: 8px;vertical-align: baseline;" icon="#bg-ic-circle-tips"></bg-icon>
            您正在对 <span class="danger_info">{{selectedRow.business_name}}</span>做删除操作。
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="handleCloseRowDelete">取消</el-button>
              <el-button type="primary" @click="deleteRowConfirm">确定</el-button>
            </span>
          </template>
        </el-dialog>
        <el-dialog
          v-model="resetFlag"
          title="重置密码"
          width="520px"
          :before-close="handleCloseReset"
        >
          <div class="warning_info">
            <bg-icon style="font-size: 12px; color: #a9b1c7; margin-right: 8px;vertical-align: baseline;" icon="#bg-ic-circle-tips"></bg-icon>
            您正在对 <span class="danger_info">{{selectedName.join('、')}}</span>做重置密码操作。
           
          </div>
           <div>
              重置密码为123456，是否继续？
            </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="handleCloseReset">取消</el-button>
              <el-button type="primary" @click="resetConfirm">确定</el-button>
            </span>
          </template>
        </el-dialog>
        <el-dialog
          v-model="editFlag"
          title="修改密码"
          width="520px"
          :before-close="handleCloseEdit"
        >
          <div class="warning_info">
            <bg-icon style="font-size: 12px; color: #a9b1c7; margin-right: 8px;vertical-align: baseline;" icon="#bg-ic-circle-tips"></bg-icon>
            您正在对 <span class="danger_info">{{selectedRow.business_name}}</span>做修改密码操作，修改后旧密码将无法登录。
           
          </div>
           <div>
             <el-form
                :label-position="'right'"
                label-width="120px"
                :model="passwordForm"
                :rules="passwordFormRules"
                ref="passwordRef"
                style="max-width: 80%"
              >
                <el-form-item label="新密码" prop="password">
                  <el-input v-model="passwordForm.password" :type="password_eye ? 'text' : 'password'" placeholder="请输入密码">
                    <template #suffix>
                      <bg-icon @click="password_eye = !password_eye" class="icon_eye"  icon="#bg-ic-eye"></bg-icon>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item label="确认新密码" prop="confirm_password">
                  <el-input v-model="passwordForm.confirm_password" :type="confirm_eye ? 'text' : 'password'" placeholder="请确认新密码"> 
                    <template #suffix>
                      <bg-icon @click="confirm_eye = !confirm_eye" class="icon_eye" icon="#bg-ic-eye"></bg-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-form>
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="handleCloseEdit">取消</el-button>
              <el-button type="primary" @click="editConfirm">确定</el-button>
            </span>
          </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue'
import { reactive, toRefs, ref, } from '@vue/reactivity'
import { getCurrentInstance, watch, nextTick } from 'vue'
import { computed, onBeforeMount } from '@vue/runtime-core'
import { useRouter } from 'vue-router';
import { edit } from 'ace-builds';
import CryptoJS from "crypto-js"; 

  const { proxy } = getCurrentInstance()
  const { $axios,$message } = proxy

  const dataTable = ref(null);
  const headers = ref([
        {
          label: "业务系统编码",
          prop: "business_code",
          width: 180
        },
        {
          label: "业务系统名称",
          prop: "business_name",
          minWidth: 180
        },
        {
          label: "账号",
          prop: "system_account",
          width: 150
        },
        {
          label: "所属机构",
          prop: "organization_name",
          width: 240
        },
        {
          label: "创建时间",
          prop: "created_time",
          width: 150
        },
        {
          label: "是否启用",
          prop: "state",
          width: 80
        },
        {
          label: "操作",
          prop: "action",
          width: 220,
          fixed: "right",
        },
      ])
  const tableRows = ref([])
  const search=ref("");
  const filter = reactive({
        search: "",
        page: 1,
        limit: 10,
      });
  const tableTotal = ref(0);
  const deleteFlag = ref(false)
  const deleteRowFlag = ref(false)
  const resetFlag = ref(false)
  const selectedRow = ref({})
  const selected = ref([])
  const selectedName = ref([])
  const editFlag = ref(false)
  const password_eye = ref(false)
  const confirm_eye = ref(false)
  const passwordRef = ref(null)
  const passwordForm = reactive({
    password: '',
    confirm_password: '',
  })
  const selectNode = ref(null)
  const filterTree = ref('')
  const treeRef = ref(null)
  const validatePass = (rule, value, callback) => {
    if (value !== passwordForm.password) {
      callback(new Error("密码输入不一致"))
    } else {
      callback()
    }
  }

  const passwordFormRules = reactive({
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      {min: 8,message: '密码长度不得低于8位',trigger: 'blur'}
    ],
    confirm_password: [
      { required: true, message: '请确认密码', trigger: 'blur' },
      { validator: validatePass, trigger: 'blur' }
    ],
  })

  const router = useRouter();

  const getTableRows = () => {
      let params = {...filter, organization_id: selectNode.value}
      $axios.get(
          `/apaas/system/v5/user/list`,
          {
            params
          }
        )
        .then((res) => {
          if (res.data.code == 200) {
            tableRows.value = res.data.data || []
            tableTotal.value = res.data.total
          }else {
            $message.error(res.data.msg)
          }
        })
  }

  const addAccount = (params) => {
    router.push({
        path: "/develop/account/add",
      })
  }

  const handleNodeClick = (data) => {
    console.log(data.data_type)
    if(data.data_type == 1) {
      selectNode.value = data.id;
      changePage(1)
    }
  }

  const orgData = ref([])
  const defaultProps = {
    label: 'name',
    children: 'Child',
    value: 'organization_id'
  }

  const  getOrgTree = () => {
    $axios.get(`/apaas/system/v5/org/tree`)
      .then((res) => {
      if (res.data.code == 200) {
          orgData.value = res.data.data || [];
          orgData.value.shift()
          const orgList = searchOrg(orgData.value);
          selectNode.value = orgList.length > 0 ? orgList[0].id : '';
          nextTick(() =>{
            if(orgList.length > 0) {
              treeRef.value.setCurrentNode(orgList[0])
            }
          })
          getTableRows()
      }else {
          $message.error(res.data.msg)
      }
      })
  }

  const searchOrg = (data) => {
    const arr = []
    data.forEach(item => {
      if(item.data_type === 1) {
        arr.push(item);
        return 
      }else {
        if(item.Child){
          searchOrg(item.Child)
        }else {
          return 
        }
      }
    })
    return arr;
  }

  watch(filterTree, (val) => {
    treeRef.value.filter(val)
  })

  const filterNode = (value, data) => {
    if (!value) return true
    return data.name.includes(value)
  }

  const stateChange = (row) => {
    const state = row.state.toString(); 
      $axios.post(
          `/apaas/system/v5/user/state/${row.id}/${state}`,
        )
        .then((res) => {
          if (res.data.code == 200) {
            getTableRows()
          }else {
            $message.error(res.data.msg)
          }
        })
  }

  const changeSize = (size) => {
    filter.limit = size;
    filter.page = 1;
    changePage(1)
  }

  const changePage = (page) => {
    filter.page = page;
    getTableRows()
  }

  const changeSearch = (val) => {
  filter.search = val
    changePage(1)
  } // 表格关键字筛选

  const goDetail = (params) => {
     router.push({
        path: "/develop/account/detail",
        query: {
          id: params.id
        }
      })
  }

  const editAccount = (id) => {
    router.push({
        path: "/develop/account/add",
        query: {
          id: id
        }
      })
  }

  const deleteAccount = (data) => {
    if(data.state === 0) {
      selectedRow.value = data;
      deleteRowFlag.value = true;
    }else {
      $message.error('当前状态已启用，不可删除！')
    }
  }

  const handleCloseDelete = () => {
      deleteFlag.value = false;
  }
  const handleCloseRowDelete = () => {
      deleteRowFlag.value = false;
  }

  const deleteConfirm = () => {
    const ids = selected.value.map(item => item.id)
     $axios.delete(
          `/apaas/system/v5/user/delete`,{data: {ids: ids}}
        )
        .then((res) => {
          if (res.data.code == 200) {
             $message.success(res.data.msg)
             getTableRows()
          }else {
            $message.error(res.data.msg)
          }
          handleCloseDelete();
        })
  }

  const deleteRowConfirm = () => {
    $axios.delete(
          `/apaas/system/v5/user/delete`,{data: {ids: [selectedRow.value.id]}}
        )
        .then((res) => {
          if (res.data.code == 200) {
             $message.success(res.data.msg)
             getTableRows()
          }else {
            $message.error(res.data.msg)
          }
          handleCloseRowDelete();
        })
  }

  const deleteBatch = () => {
    if(selectedName.value.length > 0){
      deleteFlag.value = true;
    }else {
       $message.error('请先选择需要操作的数据!')
    }
      
  }

  const handleCloseReset = () => {
      resetFlag.value = false;
  }

  const resetPsd = () => {
    if(selectedName.value.length > 0){
       resetFlag.value = true;
    }else {
       $message.error('请先选择需要操作的数据!')
    }
      
  }

  const resetConfirm = () => {
    const ids = selected.value.map(item => item.id)
     $axios.post(
          `/apaas/system/v5/user/resetpwd`,{ids: ids}
        )
        .then((res) => {
          if (res.data.code == 200) {
             $message.success(res.data.msg)
             getTableRows()
          }else {
            $message.error(res.data.msg)
          }
          handleCloseReset();
        })
  }

  const editPsdAccount = (data) => {
      selectedRow.value = data;
      editFlag.value = true;
  }

  const handleCloseEdit = () => {
      if (!passwordRef) return
            passwordRef.value.resetFields()
      editFlag.value = false;
  }
 const editConfirm = () => {
   if (!passwordRef) return
     passwordRef.value.validate((valid, fields) => {
      if (valid) {
          $axios.post(
          `/apaas/system/v5/user/editpwd`,
          {
          id: selectedRow.value.id,
          password: CryptoJS.AES.encrypt(passwordForm.password,"swuE9cmCZQwrkYRV").toString()
          }
        )
        .then((res) => {
          if (res.data.code == 200) {
             $message.success(res.data.msg)
          }else {
            $message.error(res.data.msg)
          }
          handleCloseEdit();
        })
        
      } 
    })
 }

  const selectRows = (data) => {
    selected.value = data.selection;
    selectedName.value = data.selection.map(item => item.business_name)
  }

  const clearSelected = () => {
    dataTable.value.clearSelection();
  }


  onBeforeMount(() => {
    getOrgTree()
    //getTableRows()
    
  })


</script>

<style scoped>
.tree_header {
  height: 40px;
  line-height: 40px;
	background-color: #f7f7f9;
	border-radius: 6px 6px 0px 0px;
  font-size: 16px;
	letter-spacing: 0px;
	color: #202531;
  padding-left: 16px;
}
.tree_content {
  overflow: hidden;
  height: calc(100% - 45px);
}
.search {
  padding: 16px;
}
.tree {
  overflow: auto;
  height: calc(100% - 65px);
  padding: 5px;
}
.tree :deep() .el-tree-node>.el-tree-node__children {
  overflow: unset;
}
.custom_tree_node {
  width: 100%;
  font-size: 14px;
  color: #202531;
  padding-right: 16px;
}
.label-text:hover {
  padding: 3px 0;
  background-color: var(--el-tree-node-hover-bg-color);
}
.main_container {
  padding: 15px;
  height: 100%;
}
.table_container {
  height: calc(100% - 30px);
  overflow: auto;
}

.pagination_box {
  position: sticky;
  position: -webkit-sticky;
  margin-top: 16px;
  bottom: 25px;
  background-color: #fff;
  z-index: 1024;
  height: 40px;
  line-height: 40px;
  padding-top: 5px;
}
.bg-pagination {
  bottom: unset;
  margin-top: 0px
}


</style>