<template>
    <div class="agent_page">
        <div class="title">教练管理</div>
        <div class="query adfacjb">
            <div class="left adfac">
                <el-input placeholder="请输入姓名搜索" prefix-icon="el-icon-search" v-model="queryParams.realName" style="width: 300px;" @keyup.enter.native="handleQuery"></el-input>
                <el-input type="number" placeholder="请输入手机号码搜索" prefix-icon="el-icon-search" v-model="queryParams.mobile" style="width: 300px;margin-left: 30px;" @keyup.enter.native="handleQuery"></el-input>
            </div>
            <div class="right">
                <el-button type="primary" icon="el-icon-plus" @click="handleAddCoach">添加教练</el-button>
            </div>
        </div>
        <el-table :data="userList" border cell-class-name="vertical-top-cell" v-loading="loading" empty-text="暂无教练" max-height="578px" style="margin-top: 24px;">
            <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 }">{{ gender[row.gender]||'未知' }}</template>
            </el-table-column>
            <el-table-column label="出生日期" prop="birthdate"></el-table-column>
            <el-table-column label="手机号码" prop="mobile"></el-table-column>
            <el-table-column label="教练资格类型" prop="qualificationType"></el-table-column>
            <el-table-column label="教练时长" prop="coachDuration"></el-table-column>
            <el-table-column label="教练特长" prop="talent"></el-table-column>
            <el-table-column label="创建时间" prop="createDate"></el-table-column>
            <el-table-column label="操作" width="200">
                <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>
        <el-drawer :title="userTitle" :visible.sync="userShow" append-to-body size="60%" @close="cancel">
            <el-form ref="userRef" :model="userForm" :rules="userRules" label-width="120px" style="width: 95%;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="birthdate">
                        <el-date-picker style="width: 100%;" @change="handleChangeDate"
                            v-model="userForm.birthdate"
                            type="date"
                            placeholder="请选择出生日期">
                        </el-date-picker>
                    </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="qualificationType">
                      <el-input v-model="userForm.qualificationType" placeholder="请输入教练资格类型" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="教练特长" prop="talent">
                        <el-input v-model="userForm.talent" placeholder="请输入教练特长" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="教练时长" prop="coachDuration">
                        <el-input type="number" v-model="userForm.coachDuration" placeholder="请输入教练时长(h)" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="角色配置" prop="roleIdList">
                        <el-select style="width: 100%;"
                            v-model="userForm.roleIdList"
                            multiple="true"
                            placeholder="请选择角色配置"
                            clearable
                            >
                            <el-option
                                v-for="role in roleList"
                                :key="role.id"
                                :label="role.remark"
                                :value="role.id"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
            </el-form>
            <div class="demo-drawer__footer" style="display: flex;justify-content: end;">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm" v-hasPermi="['sys:user:save']">保 存</el-button>
                <el-button @click="cancel" style="margin-right: 5%;">取 消</el-button>
            </div>
        </el-drawer>
    </div>
</template>

<script setup name="">
    import { ref, getCurrentInstance, onMounted } from 'vue'
    import { getCoachList,addCoach,updateCoach,getCoachInfo,deleteCoach } from '@/api/agent/index.js';
    const { proxy } = getCurrentInstance();
    const gender = {
        0:'男',
        1:'女',
        2:'保密'
    }
    
    const roleList = ref([])
    const queryParams = ref({
        page:1,
        limit:10,
        realName:'',
        mobile:'',
        userType:1
    })
    const userList = ref([])
    const loading = ref(false)
    const total = ref(0)
    const userShow = ref(false)
    const userTitle = ref('添加教练')
    const userForm = ref({
        id:'',
        realName:'',
        gender:'',
        birthdate:'',
        mobile:'',
        qualificationType:'',
        coachDuration:'',
        talent:'',
        roleIdList:[],
        userType:1
    })
    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[3456789]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        qualificationType: [
            { required: true, message: '请输入教练资格类型', trigger: 'blur' }
        ],
        coachDuration: [
            { required: true, message: '请输入教练时长(h)', trigger: 'blur' }
        ],
        talent: [
            { required: true, message: '请输入教练特长', trigger: 'blur' }
        ],
        roleIdList: [
            { required: true, message: '请选择角色配置', trigger: 'change' }
        ]
    })
    const buttonLoading = ref(false)
    const userRef = ref(null)

    const handleQuery = () => {
        queryParams.value.page = 1;
        getList();
    }

    const handleAddCoach = () => {
        reset();
        userTitle.value = "添加教练";
        userShow.value = true;
    }

    const reset = () => {
        userForm.value = {
            id:'',
            realName:'',
            gender:'',
            birthdate:'',
            mobile:'',
            qualificationType:'',
            coachDuration:'',
            talent:'',
            roleIdList:[],
            userType:1
        };
        proxy.resetForm("userRef");
    }

    const handleChangeDate = (e) => {
        userForm.value.birthdate = proxy.parseTime(new Date(e), '{yy}-{mm}-{dd}');
    }

    const submitForm = () => {
        proxy.$refs.userRef.validate((valid) => {
            if (valid) {
                buttonLoading.value = true;
                userForm.value.username = userForm.value.mobile;
                if(userForm.value.id){
                    updateCoach(userForm.value).then((res)=>{
                        if(res.code!==0) return proxy.$message.error(res.msg);
                        buttonLoading.value = false;
                        userShow.value = false;
                        getList();
                    })
                }else{
                    addCoach(userForm.value).then((res)=>{
                        if(res.code!==0) return proxy.$message.error(res.msg);
                        buttonLoading.value = false;
                        userShow.value = false;
                        getList();
                    })
                }
            } else {
                return false;
            }
        });
    }
    const cancel = () => {
        userShow.value = false;
        reset();
    }

    const getList = async () => {
        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;
        getList();
    }
    const handleCurrentChange = (e)=>{
        queryParams.value.page = e;
        getList();
    }

    const handleEdit = (row) => {
        reset();
        getCoachInfo(row.id).then(response => {
            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 getList();
    }
    
    const getRoleList = () => {
      return proxy.$http.get("/sys/role/list").then(({ data: res }) => {
        if (res.code !== 0) return proxy.$message.error(res.msg);
        roleList.value = res.data;
      });
    }
    onMounted(()=>{
        getList();
        getRoleList();
    })

</script>

<style scoped lang="scss">
    .agent_page{
        padding: 20px;
        box-sizing: border-box;
        .title{
            font-family: PingFang-SC, PingFang-SC;
            font-weight: bold;
            font-size: 16px;
            color: #111111;
            line-height: 16px;
        }
        .query{
            margin-top: 24px;
        }
    }

    
    :v-deep .el-dialog__wrapper{
        background: rgba(0,0,0,.3) !important;
    }
    ::v-deep .el-dialog__title{
        font-weight: bold !important;
    }
    ::v-deep .el-dialog{
        margin-top: 15vh !important;
    }
    ::v-deep .el-drawer__header span{
        font-weight: bold;
        font-size: 16px;
        color: #1D2129;
        line-height: 22px;
    }
</style>