<template>
  <div class="my">
    <el-row :gutter="20">
      <el-col :span="12" :xs="24">
        <el-card>
          <!-- 标题 -->
          <template #header>
            <div class="card-header">
              <div>个人信息</div>
            </div>
          </template>
          <div class="userDetail">
            <div class="userInfo_item">
              <div style="display: flex;align-items: center">
                <el-icon size="18" style="margin-right: 5px">
                  <User/>
                </el-icon>
                用户名:
              </div>
              <div>{{ userParams.userName }}</div>
            </div>
            <div class="userInfo_item">
              <div style="display: flex;align-items: center">
                <el-icon size="18" style="margin-right: 5px">
                  <User/>
                </el-icon>
                用户名称:
              </div>
              <div>{{ userParams.nickName }}</div>
            </div>
<!--            <div class="userInfo_item">-->
<!--              <div style="display: flex;align-items: center">-->
<!--                <el-icon size="18" style="margin-right: 5px">-->
<!--                  <Notification/>-->
<!--                </el-icon>-->
<!--                工号:-->
<!--              </div>-->
<!--              <div>{{ userParams.workCode }}</div>-->
<!--            </div>-->
<!--            <div class="userInfo_item">-->
<!--              <div style="display: flex;align-items: center">-->
<!--                <el-icon size="18" style="margin-right: 5px">-->
<!--                  <Phone/>-->
<!--                </el-icon>-->
<!--                电话号码:-->
<!--              </div>-->
<!--              <div>{{ userParams.mobile }}</div>-->
<!--            </div>-->
            <div class="userInfo_item">
              <div style="display: flex;align-items: center">
                <el-icon size="18" style="margin-right: 5px">
                  <House/>
                </el-icon>
                所属公司:
              </div>
              <div>{{ userParams.subCompanyName }}</div>
            </div>
            <div class="userInfo_item">
              <div style="display: flex;align-items: center">
                <el-icon size="18" style="margin-right: 5px">
                  <FolderOpened/>
                </el-icon>
                所属部门:
              </div>
              <div>{{ userParams.departmentName }}</div>
            </div>
            <div class="userInfo_item">
              <div style="display: flex;align-items: center">
                <el-icon size="18" style="margin-right: 5px">
                  <Folder/>
                </el-icon>
                岗位:
              </div>
              <div>{{ userParams.jobActivityDesc }}</div>
            </div>
            <div class="userInfo_item">
              <div style="display: flex;align-items: center">
                <el-icon size="18" style="margin-right: 5px">
                  <Wallet/>
                </el-icon>
                账号类型:
              </div>
              <div>{{ userParams.accountType === '0' ? '主账号' : '次账号' }}</div>
            </div>
            <div class="userInfo_item">
              <div style="display: flex;align-items: center">
                <el-icon size="18" style="margin-right: 5px">
                  <User/>
                </el-icon>
                所属角色:
              </div>
              <div>{{ belongToRole(userParams.roles) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-card>
        <baseTitle title="设置代理" ></baseTitle>
        <el-form ref="userForm" :model="agentInfoForm" label-width="85px">
          <el-row gutter="30">
            <el-col :span="24">
              <el-form-item label="被代理人" prop="nickName">
                <span>{{ agentInfoForm.nickName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="代理人" prop="" required >
                <el-button style="margin-right: 10px" color="#DED0B2" @click="handleShowAgentDialog">
                  {{ agentUserList?.length !== 0 ? '更改' : '请选择' }}
                </el-button>
                <div v-for="item in agentUserList" :key="item.id" style="margin-right: 5px">
                  {{ item.name }}
                </div>
                <user-picker :multiple="false" ref="agentUserPickerRef" title="请选择代理人"
                             v-model:value="agentUserList" @ok="agentUserPickerOk"
                             @cancelOrClear="agentUserPickerOk"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="代理状态" prop="agentState">
                <Tag dictType="agent_state" :value="agentInfoForm.agentState"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="开始时间" prop="agentStartTime">
                <el-config-provider>
                  <el-date-picker
                      v-model="agentInfoForm.agentStartTime"
                      type="datetime"
                      placeholder="请选择开始时间"
                      value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-config-provider>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="结束时间" prop="agentEndTime" :title="!agentInfoForm.agentStartTime?'请先选择开始时间!':''">
                <el-config-provider>
                  <el-date-picker
                      v-model="agentInfoForm.agentEndTime"
                      type="datetime"
                      placeholder="请选择结束时间"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      :disabled="!agentInfoForm.agentStartTime"
                      :disabled-date="disabledAgentEndTime"
                  />
                </el-config-provider>
              </el-form-item>
            </el-col>
            <el-form-item>
                <el-button color="#DED0B2" @click="handleSubmitAgent" style="margin-left: 16px">提交</el-button>
            </el-form-item>
          </el-row>
        </el-form>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12" :xs="24">
        <el-card class="box-card">
          <!-- 标题 -->
          <template #header>
            <div class="card-header">
              <div>{{ isInitPassword ? '修改密码' : '初始化密码' }}</div>
            </div>
          </template>
          <el-form label-width="120px" ref="passwordRef" :model="userPassword" :rules="rules">
            <el-form-item label="旧密码" prop="oldPassword" :required="true" style="text-align:left" v-if="isInitPassword">
              <el-input placeholder="请输入旧密码" v-model="userPassword.oldPassword" type="password"/>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword" :required="true" style="text-align:left">
              <el-input placeholder="请输入新密码" v-model="userPassword.newPassword" type="password"/>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword" :required="true" style="text-align:left">
              <el-input placeholder="请确认新密码" v-model="userPassword.confirmPassword" type="password"/>
            </el-form-item>
            <el-form-item>
              <el-button color="#DED0B2" @click="handleSubmitPassword">提交</el-button>
              <el-button @click="closeIndividualCenter">关闭</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script setup>
import {ElNotification} from 'element-plus'
import {useTagsView} from '@/stores/tagsview.js'
import {getAuthInfo} from "@/api/login";
import {editPassword, initPassword,getAgentInfo,editAgentInfo} from "@/api/auth/auth";
import UserPicker from "@/views/workflow/process/common/UserPicker.vue";

const router = useRouter()
const tagsViewStore = useTagsView()
const isInitPassword = ref(false);
const agentUserList = ref([])
const agentUserPickerRef = ref()
const userParams = ref({});
const passwordRef = ref();
const agentInfoForm = ref({});
const userPassword = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

const validatePasswordComplexity = (rule, value, callback) => {
  const reg = /^(?=.*[a-zA-Z])(?=.*\d).{1,9}$/; //密码必须是至少包含字母、数字，1-9位
  if (!reg.test(value)) {
    callback(new Error("密码必须是至少包含字母、数字，1-9位"));
  } else {
    callback();
  }
};


const validatePasswordEquality = (rule, value, callback) => {
  if (userPassword.value.newPassword != value) {
    callback(new Error("两次输入密码不一致!"));
  } else {
    callback();
  }
}
const rules = reactive({
  oldPassword: [
    {required: true, message: "旧密码不能为空", trigger: ["change", "blur"]},
  ],
  newPassword: [
    {required: true, message: "新密码不能为空", trigger: ["change", "blur"]},
    {
      required: true,
      trigger: ["change", "blur"],
      validator: validatePasswordComplexity
    }
  ],
  confirmPassword: [
    {required: true, message: "确认密码不能为空", trigger: ["change", "blur"]},
    {
      required: true,
      trigger: ["change", "blur"],
      validator: validatePasswordEquality
    }
  ],
})
const disabledAgentEndTime = (time) => {
  return time.getTime() <= new Date(agentInfoForm.value.agentStartTime)-1 * 24 * 3600 * 1000
}

const handleShowAgentDialog = () => {
  agentUserPickerRef.value.showUserPicker()
}

const agentUserPickerOk = (userList) => {
  console.info("🚀 ~method:userList -----", userList)
  agentUserList.value = userList
}
const getUserInfo = async () => {
  await getAuthInfo().then(res => {
    if(res.code===1000){
      userParams.value = res.data.user
      isInitPassword.value = res.data.initPassword
    }else {
      ElNotification({
        title: '提示',
        message: res.msg,
        type:  'error'
      })
    }
  })
}

const getUserAgentInfo = async () => {
  await getAgentInfo().then(res => {
    if(res.code===1000){
      agentInfoForm.value=res.data
      if(res.data.agentUserId){
        agentUserList.value=[
          {
            id:res.data.agentUserId,
            name:res.data.agentNickName,
            companyName:res.data.agentCompanyName,
          }
        ]
      }
    }else {
      ElNotification({
        title: '提示',
        message: res.msg,
        type:  'error'
      })
    }
  })
}
localStorage.removeItem('originallySelectedList')

const belongToRole = (roles) => {
  if (!roles) return;
  return roles.map(item => item.roleName).join('，')
}
const handleSubmitAgent=()=>{
  let agentUserId=''
  if(agentUserList.value&&agentUserList.value.length>0){
    agentUserId=agentUserList.value[0]?.id
  }else {
    ElNotification({
      title: '提示',
      message: '请选择代理人!',
      type: 'error'
    })
    return;
  }
  let agentParams={
    agentUserId:agentUserId,
    agentStartTime:agentInfoForm.value.agentStartTime,
    agentEndTime:agentInfoForm.value.agentEndTime
  }
  console.info("🚀 ~method:agentParams -----", agentParams)
  editAgentInfo(agentParams).then(res => {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: res.code === 1000 ? 'success' : 'error'
    })
    if (res.code === 1000) {
      getUserAgentInfo()
    }
  })
}
// 修改密码
const handleSubmitPassword = async () => {
  if (isInitPassword.value) {
    editPassword({
      ...userPassword.value
    }).then(res => {
      ElNotification({
        title: '提示',
        message: res.msg,
        type: res.code === 1000 ? 'success' : 'error'
      })
      if (res.code === 1000) {
        passwordRef.value.resetFields()
      }
    })
  } else {
    initPassword({
      newPassword: userPassword.value.newPassword,
      confirmPassword: userPassword.value.confirmPassword
    }).then(res => {
      ElNotification({
        title: '提示',
        message: res.msg,
        type: res.code === 1000 ? 'success' : 'error'
      })
      if (res.code === 1000) {
        passwordRef.value.resetFields()
      }
    })
  }
}
// 关闭
const closeIndividualCenter = () => {
  tagsViewStore.delVisitedViews(router.currentRoute.value.path)
  router.push('/')
}
onMounted(() => {
  getUserInfo()
  getUserAgentInfo()
})
</script>
<style lang="scss">
.box-card {
  //margin-left: 10px;
  margin-top: 10px;
}

body, div {
  margin: 0;
  padding: 0;
}

.my {
  margin: 20px auto 0;

  .userDetail {
    .userImg {
      height: 170px;
      text-align: center;
      border-bottom-style: solid;
      border-color: #daddd2;
      border-width: 1px;

      .avatar {
        width: 150px;
        height: 150px;
        border-radius: 50%;
      }
    }
  }

  .userInfo_item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 40px;
    border-bottom-style: solid;
    border-color: #daddd2;
    border-width: 1px;
  }
}

</style>
