<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div class="search" v-show="showSearch">
                <el-form :model="queryParams" ref="queryFormRef" label-width="100px">
                    <el-row :gutter="15">
                        <el-col :xl="6" :lg="8" :sm="12">
                            <el-form-item label="企业名称" prop="cpyName">
                                <el-input v-model="queryParams.cpyName" placeholder="请输入企业名称" clearable @keyup.enter="handleQuery" />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8" :sm="12">
                            <el-form-item label="电话" prop="tel">
                                <el-input v-model="queryParams.tel" placeholder="请输入电话" clearable @keyup.enter="handleQuery" />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8" :sm="12">
                            <el-form-item label="信用代码" prop="creditCode">
                                <el-input v-model="queryParams.creditCode" placeholder="请输入信用代码" clearable @keyup.enter="handleQuery" />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8" :sm="12">
                            <el-form-item label="审核状态" prop="status">
                                <el-select v-model="queryParams.status" style="width: 100%;" placeholder="请选择审核状态" clearable>
                                    <el-option v-for="dict in cpy_res_status" :key="dict.value" :label="dict.label" :value="dict.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8" :sm="12">
                            <el-form-item>
                                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </transition>
        <el-card shadow="never">
            <!-- <template #header>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['enterprise:recordCompany:add']">新增</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button
                            type="success"
                            plain
                            icon="Edit"
                            :disabled="single"
                            @click="handleUpdate()"
                            v-hasPermi="['enterprise:recordCompany:edit']"
                            >修改</el-button
                        >
                    </el-col>
                    <el-col :span="1.5">
                        <el-button
                            type="danger"
                            plain
                            icon="Delete"
                            :disabled="multiple"
                            @click="handleDelete()"
                            v-hasPermi="['enterprise:recordCompany:remove']"
                            >删除</el-button
                        >
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['enterprise:recordCompany:export']"
                            >导出</el-button
                        >
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </template> -->
            <el-table v-loading="loading" :data="recordCompanyList" border @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="企业名称" align="center" prop="cpyName" />
                <el-table-column label="企业logo" align="center" prop="license" width="100">
                    <template #default="scope">
                        <template v-if="scope.row.storePhoto && typeof scope.row.storePhoto === 'string'">
                            <image-preview :src="scope.row.storePhoto" :width="50" :height="50" />
                        </template>
                        <template v-else>
                            <span>暂无图片</span>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column label="信用代码" align="center" prop="creditCode" />
                <el-table-column label="营业执照" align="center" prop="license" width="100">
                    <template #default="scope">
                        <template v-if="scope.row.license && scope.row.license.url">
                            <image-preview :src="scope.row.license.url" :width="50" :height="50" />
                        </template>
                    </template>
                </el-table-column>
                <el-table-column label="所在行政区" align="center" prop="adcdCode">
                    <template #default="{ row }">
                        <AreaView :value="row.adcdCode"></AreaView>
                    </template>
                </el-table-column>
                <el-table-column label="合作伙伴" align="center" prop="partnerName" />
                <el-table-column label="具体地址" align="center" prop="address" />
                <el-table-column label="联系人姓名" align="center" prop="contactPerson" />
                <el-table-column label="电话" align="center" prop="tel" />
                <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip width="110">
                    <template #default="scope">
                        <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="更新时间" align="center" prop="updateTime" show-overflow-tooltip width="110">
                    <template #default="scope">
                        <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="审核状态" fixed="right" align="center" prop="status">
                    <template #default="{ row }">
                        <div>{{ selectDictLabel(cpy_res_status, row.status) }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" min-width="160" fixed="right" class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-tooltip content="修改" placement="top">
                            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['enterprise:recordCompany:edit']"></el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['enterprise:recordCompany:remove']"></el-button>
                        </el-tooltip>
                        <template v-if="scope.row.status * 1 === 0">
                            <el-tooltip content="审核通过" placement="top">
                                <el-button link type="primary" icon="CircleCheck" @click="handleApproval(scope.row, '1')" v-hasPermi="['enterprise:recordCompany:edit']"></el-button>
                            </el-tooltip>
                            <el-tooltip content="审核不通过" placement="top">
                                <el-button link type="danger" icon="CircleClose" @click="handleApproval(scope.row, '2')" v-hasPermi="['enterprise:recordCompany:edit']"></el-button>
                            </el-tooltip>
                        </template>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-card>
        <!-- 添加或修改企业备案信息对话框 -->
        <el-dialog :close-on-click-modal="false" :title="dialog.title" v-model="dialog.visible" width="700px" append-to-body>
            <el-form ref="recordCompanyFormRef" :model="form" :rules="rules" label-width="auto">
                <div class="mb20">
                    <UploadAvatar title="企业logo" v-model="form.storePhoto"></UploadAvatar>
                    <div class="t-a-c">企业logo</div>
                </div>
                <el-form-item prop="cpyName" label="企业名称">
                    <el-input v-model="form.cpyName" class="base-input" placeholder="请填写企业名称" />
                </el-form-item>
                <el-form-item prop="cpyType" label="企业类型">
                    <el-radio-group v-model="form.cpyType">
                        <el-radio v-for="item in cpy_type" :key="item.value" :label="item.value" :value="item.value">
                            {{ item.label }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <template v-if="form.cpyType === '13'">
                    <el-form-item prop="supervisionType" label="具体类型">
                        <el-radio-group v-model="form.supervisionType">
                            <el-radio v-for="item in supervision_type" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item prop="supervisionArea" label="监管区域">
                        <AreaCascader :zlevel="2" v-model="form.supervisionArea" checkStrictly></AreaCascader>
                    </el-form-item>
                </template>
                <el-form-item prop="creditCode" label="统一社会信用代码">
                    <el-input v-model="form.creditCode" maxlength="18" class="base-input" placeholder="请填写18位统一社会信用代码" />
                </el-form-item>
                <el-form-item prop="license" label="营业执照">
                    <div class="flex1">
                        <FileUpload v-model="form.license" format="object" :isFile="false" :span="20" :limit="1" :fileType="['png', 'jpg', 'jpeg']"></FileUpload>
                    </div>
                </el-form-item>
                <el-form-item prop="adcdCode" label="所在行政区">
                    <AreaCascader :zlevel="2" v-model="form.adcdCode"></AreaCascader>
                </el-form-item>
                <el-form-item prop="address" label="具体地址">
                    <el-input v-model="form.address" class="base-input" placeholder="请填写区县以下的具体企业地址信息" />
                </el-form-item>
                <el-form-item prop="contactPerson" label="企业联系人">
                    <el-input v-model="form.contactPerson" class="base-input" placeholder="请填写企业联系人姓名" />
                </el-form-item>
                <el-form-item prop="tel" label="企业联系电话">
                    <el-input v-model="form.tel" class="base-input" maxlength="11" placeholder="请填写企业联系电话" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="RecordCompany" lang="ts">
import {
    listRecordCompany,
    getRecordCompany,
    delRecordCompany,
    addRecordCompany,
    updateRecordCompany,
    companyApproval
} from '@/api/enterprise/recordCompany';
import { RecordCompanyVO, RecordCompanyQuery, RecordCompanyForm } from '@/api/enterprise/recordCompany/types';
import { AreaCascader, UploadAvatar, AreaView } from '@/views/components';
import { CircleCheck, CircleClose } from '@element-plus/icons-vue';
import { Action } from 'element-plus';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { cpy_res_status, cpy_type, supervision_type } = toRefs<any>(proxy?.useDict('cpy_res_status', 'cpy_type', 'supervision_type'));
const recordCompanyList = ref<RecordCompanyVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const recordCompanyFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});

const initFormData: RecordCompanyForm = {
    storePhoto: undefined,
    cpyName: undefined,
    creditCode: undefined,
    license: undefined,
    cpyType: undefined,
    adcdCode: undefined,
    address: undefined,
    contactPerson: undefined,
    tel: undefined,
    supervisionType: undefined
};
const data = reactive<PageData<RecordCompanyForm, RecordCompanyQuery>>({
    form: { ...initFormData },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        cpyName: undefined,
        tel: undefined,
        creditCode: undefined,
        status: '0'
    },
    rules: {
        storePhoto: [{ required: true, trigger: 'blur', message: '请上传企业logo' }],
        cpyName: [{ required: true, trigger: 'blur', message: '请填写企业名称' }],
        creditCode: [{ required: true, trigger: 'blur', message: '请填写18位统一社会信用代码' }],
        license: [{ required: true, trigger: 'blur', message: '请上传营业执照' }],
        cpyType: [{ required: true, trigger: 'blur', message: '请选择结构类型' }],
        adcdCode: [{ required: true, trigger: 'blur', message: '请选择所在行政区' }],
        address: [{ required: true, trigger: 'blur', message: '请填写具体地址' }],
        contactPerson: [{ required: true, trigger: 'blur', message: '请填写企业联系人姓名' }],
        tel: [{ required: true, trigger: 'blur', message: '请填写企业联系电话' }]
    }
});

const { queryParams, form, rules } = toRefs(data);
// 审批办理
const handleApproval = async (row: any, res: string) => {
    const { cpyName } = row;
    if (res === '1') {
        ElMessageBox.confirm('企业审核通过?', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'success',
            icon: markRaw(CircleCheck)
        })
            .then(() => {
                const params = {
                    targetType: 'cpy',
                    targetId: row.id,
                    res
                };
                approvalAjax(params);
            })
            .catch(() => {
                proxy?.$modal.msgWarning('取消审核');
            });
    } else {
        ElMessageBox.prompt('企业审核不通过', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            inputPlaceholder: '不通过理由',
            inputErrorMessage: '请填写不通过理由',
            type: 'error',
            icon: markRaw(CircleClose),
            inputValidator: (value) => {
                return value ? true : false
            }
        })
            .then(({ value }) => {
                const params = {
                    targetType: 'cpy',
                    targetId: row.id,
                    res,
                    msg: value
                };
                approvalAjax(params);
            })
            .catch(() => {
                proxy?.$modal.msgWarning('取消审核');
            });
    }
};
const approvalAjax = async (params: any) => {
    proxy?.$modal.loading('审核中...')
    const res = await companyApproval(params).catch(() => { });
    proxy?.$modal.closeLoading()
    if (!res) return;
    proxy?.$modal.msgSuccess('操作完成')
    getList()
};
/** 查询企业备案信息列表 */
const getList = async () => {
    loading.value = true;
    const res = await listRecordCompany(queryParams.value);
    recordCompanyList.value = res.rows;
    total.value = res.total;
    loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
    reset();
    dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
    form.value = { ...initFormData };
    recordCompanyFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: RecordCompanyVO[]) => {
    ids.value = selection.map((item) => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = '添加企业备案信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: RecordCompanyVO) => {
    reset();
    const _id = row?.id || ids.value[0];
    const res = await getRecordCompany(_id);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = '修改企业备案信息';
};

/** 提交按钮 */
const submitForm = () => {
    recordCompanyFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            if (form.value.id) {
                await updateRecordCompany(form.value).finally(() => (buttonLoading.value = false));
            } else {
                await addRecordCompany(form.value).finally(() => (buttonLoading.value = false));
            }
            proxy?.$modal.msgSuccess('修改成功');
            dialog.visible = false;
            await getList();
        }
    });
};

/** 删除按钮操作 */
const handleDelete = async (row?: RecordCompanyVO) => {
    const _ids = row?.id || ids.value;
    await proxy?.$modal.confirm('是否确认删除企业备案信息编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
    await delRecordCompany(_ids);
    proxy?.$modal.msgSuccess('删除成功');
    await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
    proxy?.download(
        'enterprise/recordCompany/export',
        {
            ...queryParams.value
        },
        `recordCompany_${new Date().getTime()}.xlsx`
    );
};

onMounted(() => {
    getList();
});
</script>
