<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="search"
                    placeholder="请输入组织名称搜索"
                    :prefix-icon="Search"
                  />
               </div>
               <div class="tree">
                 <el-tree :data="orgData" :props="defaultProps" @node-click="handleNodeClick" :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="getTableRows" 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 name_btn" @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="name_btn">
                        {{ 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="btn" @click="editAccount(row.id)">
                        编辑
                      </bg-table-btn>
                      <bg-table-btn class="btn" @click="editPsdAccount(row)">
                        修改密码
                      </bg-table-btn>
                      <bg-table-btn class="btn"  @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 } 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 validatePass = (rule, value, callback) => {
    if (value !== passwordForm.password) {
      callback(new Error("密码输入不一致"))
    } else {
      callback()
    }
  }

  const passwordFormRules = reactive({
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
    ],
    confirm_password: [
      { required: true, message: '请确认密码', trigger: 'blur' },
      { validator: validatePass, trigger: 'blur' }
    ],
  })

  const router = useRouter();

  const getTableRows = () => {
      let params = {...filter}
      $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)
  }

  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 || [];
      }else {
          $message.error(res.data.msg)
      }
      })
  }

  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;
    getTableRows()
  }

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

  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) => {
     selectedRow.value = data;
     deleteRowFlag.value = true;
  }

  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
}
.warning_info {
  background-color: #f7f7f9;
  font-size: 14px;
	color: #404a62;
  padding: 5px;
  text-align: left;
  margin: 20px 0;
}
.danger_info {
  color: #d75138;
}

</style>