<template>
    <div class="full_page">
        <div class="content">
            <div class="top adfac">
                <div class="t_l adfac">
                    <img src="@/assets/images/agent/arrow_left.png" @click="handleBack">
                    <div class="spans">
                        <span>项目管理</span>
                        <span class="last">&nbsp;/&nbsp;成员管理</span>
                    </div>
                </div>
            </div>
            <div class="c_bottom adf">
                <div class="cb_l">
                    <el-select v-model="programid" placeholder="请选择项目" @change="handleChange">
                        <el-option v-for="item in useAgentStore().companyList" :key="item.id" :label="item.enterpriseName" :value="item.id"></el-option>                        
                    </el-select>
                    <div class="cbl_list">
                        <div class="cbl_item" :class="{'active':tidx===index}" v-for="(item, index) in teamList" :key="index" @click="handleTeam(item,index)">
                            {{ item.teamName }}
                        </div>
                    </div>
                </div>
                <div class="cb_r">
                    <div class="cbr_top adfacjb">
                        <div class="ct_l">团队成员</div>
                        <div class="ct_r adfac">
                            <div class="tr_btn" @click="handleDownloadExcel" v-hasPermi="['core:project:downloadExcel']" v-if="programid&&teamid">模板下载</div>
                            <el-upload v-if="programid&&teamid"
                                :action="uploadUrl"
                                :data="{enterpriseId: programid, teamId: teamid}"
                                :headers="uploadHeaders"
                                :before-upload="handleBeforeUpload"
                                :on-success="handleSuccess"
                                >
                                <div class="tr_btn" v-hasPermi="['sys:user:export']">导入成员</div>
                            </el-upload> 
                            <div class="tr_btn" @click="handleAddUser" v-hasPermi="['sys:user:add']">添加成员</div>
                        </div>
                    </div>
                    <el-table :data="userList" border cell-class-name="vertical-top-cell" v-loading="loading" empty-text="暂无人员" max-height="578px" style="margin-top: 16px;">
                        <el-table-column label="序号" width="50">
                            <template #default="scope">
                                {{ scope.$index + 1 }}
                            </template>
                        </el-table-column>
                        <el-table-column label="姓名" prop="realName"></el-table-column>
                        <el-table-column label="性别" prop="gender">
                            <template #default="{ row }">{{ genderCfg[row.gender]||'未知' }}</template>
                        </el-table-column>
                        <el-table-column label="类型" prop="category">
                            <template #default="{ row }">{{ UserCategory.find(u=>u.value===row.category)?.label ||'未知' }}</template>
                        </el-table-column>
                        <el-table-column label="人物简介" prop="introduction" width="400" show-overflow-tooltip></el-table-column>
                        <el-table-column label="人物故事" prop="userStory" width="400" show-overflow-tooltip></el-table-column>
                        <el-table-column label="操作" width="150">
                            <template #default="scope">
                                <el-button link type="text" size="mini" @click="handleEdit(scope.row)" v-hasPermi="['sys:user:update']">编辑</el-button>
                                <el-button link type="text" size="mini" @click="handleDelete(scope.row)" v-hasPermi="['sys:user:delete']">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-row style="display: flex;justify-content: center;">
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="queryParams.page"
                            :page-sizes="[5, 10, 20, 50]"
                            :page-size="10"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total"
                            v-show="total > 0">
                        </el-pagination>
                    </el-row>
                </div>
            </div>
        </div>
        <el-drawer :title="userTitle" :visible.sync="userShow" append-to-body size="60%" @close="userShow=false">
            <el-form ref="userRef" :model="userForm" :rules="userRules" label-width="100px" style="width: 90%;margin: 0 auto;">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="姓名" prop="realName">
                      <el-input v-model="userForm.realName" placeholder="请输入姓名" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="性别" prop="gender">
                        <el-select v-model="userForm.gender" placeholder="请选择性别" style="width: 100%;">
                            <el-option label="男" :value="0"></el-option>
                            <el-option label="女" :value="1"></el-option>
                            <el-option label="保密" :value="2"></el-option>
                        </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                        <el-form-item label="类型" prop="category">
                            <el-select v-model="userForm.category" placeholder="请选择类型" style="width: 100%;">
                                <el-option v-for="item in UserCategory" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="手机号码" prop="mobile">
                      <el-input type="number" v-model="userForm.mobile" placeholder="请输入手机号码" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="所属部门" prop="dept">
                      <el-input v-model="userForm.dept" placeholder="请输入所属部门" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="教育程度" prop="education">
                        <el-input v-model="userForm.education" placeholder="请输入教育程度" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="分工" prop="divisionOfLabour">
                      <el-input v-model="userForm.divisionOfLabour" placeholder="请输入分工" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="职位" prop="post">
                      <el-input v-model="userForm.post" placeholder="请输入职位" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="级别" prop="level">
                        <el-input v-model="userForm.level" placeholder="请输入级别" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="人物简介" prop="introduction">
                        <el-input type="textarea" :rows="2" v-model="userForm.introduction" placeholder="请输入人物简介" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="人物故事" prop="userStory">
                        <el-input type="textarea" :rows="2" v-model="userForm.userStory" placeholder="请输入人物故事" />
                    </el-form-item>
                  </el-col>
                </el-row>
            </el-form>
            <div class="demo-drawer__footer" style="display: flex;justify-content: end;">
                <el-button :loading="buttonLoading2" type="primary" @click="submitForm2" v-hasPermi="['sys:user:save']">保 存</el-button>
                <el-button @click="cancel2" style="margin-right: 5%;">取 消</el-button>
            </div>
        </el-drawer>
    </div>
</template>

<script setup name="">
    import Cookies from "js-cookie";
    import { ref, getCurrentInstance, onMounted } from 'vue'
    const { proxy } = getCurrentInstance();
    import {useAgentStore} from "@/store_v3/modules/agent";
    useAgentStore().getCompanyData();
    import { 
        getCoachList,
        updateCoach,
        getCoachInfo,
        deleteCoach,
        addCoach,
        getTeamListById,
    } from '@/api/agent/index.js'

    const uploadUrl = `${window.SITE_CONFIG["apiURL"]}/sys/user/import`
    const uploadHeaders = {token:Cookies.get("token")}; 
    const { companyIndustry, staffSize, UserCategory} = proxy.useDict("companyIndustry", "staffSize", "UserCategory");
    
    const programid = ref('')
    const teamid = ref('')
    const teamList = ref([]);
    const tidx = ref('')
    const userList = ref([]);
    const total = ref(0);
    const loading = ref(false);
    const genderCfg = {
        '0': '男',
        '1': '女',
        '2': '保密',
    }
    const userTitle = ref('添加成员信息');
    const userShow = ref(false);
    const buttonLoading2 = ref(false);
    const userRef = ref(null);
    const queryParams = ref({
        page:1,
        limit:10,
        teamId:'',
        realName:'',
    })
    const userForm = ref({
        id:'',
        enterpriseId:'',
        teamId:'',
        realName:'',
        username:'',
        gender:'',
        birthdate:'',
        mobile:'',
        dept:'',
        education:'',
        divisionOfLabour:'',
        post:'',
        level:'',
        userType:2,
        category:'',
        introduction:'',
        userStory:''
    });
    const userRules = ref({
        realName: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        gender: [
            { required: true, message: '请选择性别', trigger: 'change' }
        ],
        birthdate: [
            { required: true, message: '请选择出生日期', trigger: 'change' }
        ],
        mobile: [
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        dept: [
            { required: true, message: '请输入所属部门', trigger: 'blur' }
        ],
        education: [
            { required: true, message: '请输入教育程度', trigger: 'blur' }
        ],
        divisionOfLabour: [
            { required: true, message: '请输入分工', trigger: 'blur' }
        ],
        post: [
            { required: true, message: '请输入职位', trigger: 'blur' }
        ],
        level:[
            { required: true, message: '请输入级别', trigger: 'blur' }
        ],
        category:[
            { required: true, message: '请选择成员类型', trigger: 'change' }
        ],
        introduction:[
            { required: true, message: '请输入成员简介', trigger: 'blur' }
        ],
        userStory:[
            { required: true, message: '请输入成员故事', trigger: 'blur' }
        ]
    });

    const handleBack = () => {
        proxy.$router.back()
    }

    const handleBeforeUpload = (e,node,data)=>{
        let type = e.name.split('.')[e.name.split('.').length-1];
        let isExcel = e.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        if(type.toLowerCase() !== 'xlsx' && type.toLowerCase() !== 'xls' && !isExcel){
            proxy?.$modal.msgError('请上传xlsx或xls格式的Excel文件！');
            return false;
        }
        setTimeout(()=>{
            getUserList();
        },1000)
    }

    const handleSuccess = (e,node,data)=>{
        if(e.code===0){
            proxy?.$modal.msgSuccess('导入成功！'+e.msg);
        }else {
            proxy?.$modal.msgError('导入失败！'+e.msg);
        }
    }

    const handleChange = (val) => {
        programid.value = val;
        getTeamListByCompanyId();
    }

    const getTeamListByCompanyId = ()=> {
        getTeamListById({enterpriseId: programid.value}).then(res=>{
            if(res.code!==0) proxy.$message.error(res.msg);
            teamList.value = res.data;
            if(teamid.value){
                let idx = teamList.value.findIndex(item=>{
                    return item.id === teamid.value;
                });
                if(idx>-1){
                    tidx.value = idx;
                }
            }
        })
    }

    const handleTeam = (item, index) => {
        tidx.value = index;
        teamid.value = item.id;
        getUserList();
    }

    const getUserList = async () => {
        queryParams.value.teamId = teamid.value;
        let query = {...queryParams.value};
        loading.value = true;
        const res = await getCoachList(query);
        userList.value = res.data.list;
        total.value = res.data.total;
        loading.value = false;
    }

    const handleSizeChange = (e)=>{
        queryParams.value.limit = e;
        getUserList();
    }
    const handleCurrentChange = (e)=>{
        queryParams.value.page = e;
        getUserList();
    }

    const handleDownloadExcel = () => {
        window.location.href = `${window.SITE_CONFIG["apiURL"]}/sys/user/download?token=${Cookies.get("token")}`;
    }

    const handleAddUser = () => {
        if(!teamid.value) return proxy.$message.error('请先选择团队');
        reset();
        userTitle.value = "新增成员详情";
        userShow.value = true;
    }
    
    const reset = () => {
        userForm.value = {
            id:'',
            enterpriseId:'',
            teamId:'',
            realName:'',
            username:'',
            gender:'',
            birthdate:'',
            mobile:'',
            dept:'',
            education:'',
            divisionOfLabour:'',
            post:'',
            level:'',
            userType:2,
            category:'',
            introduction:'',
            userStory:''
        };
        proxy.resetForm("userRef");
    }
    
    const submitForm2 = () => {
        proxy.$refs.userRef.validate((valid) => {
            if (valid) {
                buttonLoading2.value = true;
                userForm.value.username = userForm.value.mobile;
                userForm.value.enterpriseId = programid.value;
                userForm.value.teamId = teamid.value;
                if(userForm.value.id){
                    updateCoach(userForm.value).then((res)=>{
                        if(res.code!==0) return proxy.$message.error(res.msg);
                        buttonLoading2.value = false;
                        userShow.value = false;
                        getUserList();
                    })
                }else{
                    addCoach(userForm.value).then((res)=>{
                        if(res.code!==0) return proxy.$message.error(res.msg);
                        buttonLoading2.value = false;
                        userShow.value = false;
                        getUserList();
                    })
                }
            } else {
                return false;
            }
        });
    }

    const cancel2 = () => {
        userShow.value = false;
        reset();
    }
    
    const handleEdit = (row) => {
        reset();
        getCoachInfo(row.id).then(response => {
            userForm.value = {...userForm.value,...response.data};
            userTitle.value = "编辑成员详情";
            userShow.value = true;
        });
    }
    async function handleDelete(row) {
        await proxy?.$modal.confirm('确认删除成员【' + row.realName + '】吗？').finally(() => loading.value = false);
        let res = await deleteCoach([row.id]);
        if (res.code === 0) proxy?.$modal.msgSuccess("删除成功");
        else return proxy?.$modal.msgError(res.msg);
        await getUserList();
    }

    onMounted(()=>{
        programid.value = proxy.$route?.query?.enterpriseId;
        teamid.value = proxy.$route?.query?.teamId;
        getTeamListByCompanyId();
        getUserList();
    })
</script>

<style scoped lang="scss">
    .full_page{
        background: #FAFAFA;

        .content{
            width: calc(100% - 24px);
            height: calc(100vh - 30px);
            margin: 12px;
            background: #FFFFFF;
            border-radius: 6px 6px 0px 0px;
            border: 1px solid #F3F4F6;
            position: relative;
            display: flex;
            flex-direction: column;

            .top{
                width: 100%;
                height: 64px;
                background: #FFFFFF;
                border-bottom: 1px solid #F3F4F6;
                .t_l{
                    width: 310px;
                    img{
                        width: 36px;
                        height: 36px;
                        margin-left: 16px;
                        cursor: pointer;
                    }
                    .spans{
                        display: flex;
                        align-items: center;
                        margin-left: 23px;
                        span{
                            font-family: PingFangSC, PingFang SC;
                            font-weight: 400;
                            font-size: 14px;
                            color: #6B7280;
                            line-height: 14px;
                            &.last{
                                color: #111111;
                            }
                        }
                    }
                }
            }

            .c_bottom{
                width: 100%;
                flex: 1;
                display: flex;
                .cb_l{
                    width: 280px;
                    height: 100%;
                    border-right: 1px solid #E5E7EB;
                    padding: 24px 16px;
                    box-sizing: border-box;

                    .cbl_list{
                        margin-top: 24px;
                        width: 100%;
                        flex: 1;
                        overflow-y: auto;
                        .cbl_item{
                            width: 100%;
                            padding: 24px 16px;
                            box-sizing: border-box;
                            box-shadow: inset 0px -1px 0px 0px #EFEFEF;
                            font-family: PingFangSC, PingFang SC;
                            font-weight: 400;
                            font-size: 14px;
                            color: #252525;
                            line-height: 14px;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            white-space: nowrap;
                            cursor: pointer;
                            &.active,&:hover{
                                background: rgba(118,30,106,0.06);
                                font-weight: bold;
                                color: #761E6A;
                            }
                        }
                    }
                }
                .cb_r{
                    padding: 30px 16px 24px;
                    flex: 1;
                    box-sizing: border-box;
                    .ct_l{
                        font-family: PingFang-SC, PingFang-SC;
                        font-weight: bold;
                        font-size: 16px;
                        color: #252525;
                        line-height: 16px;
                    }
                    .ct_r{
                        .tr_btn{
                            width: 92px;
                            height: 36px;
                            border-radius: 6px;
                            border: 1px solid #C1C7D2;
                            margin-left: 20px;
                            cursor: pointer;
                            font-family: PingFangSC, PingFang SC;
                            font-weight: 400;
                            font-size: 14px;
                            color: #111111;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            &:last-child{
                                background: #761E6A;
                                color: #FFFFFF;
                            }
                        }
                    }
                }
            }
        }
    }
</style>