<template>
    <div>
        <crud-template v-if="itemStart" class="as-weight" :ref="(el) => (crudRef = el)" :home-data="field"
            @btnSearch="btnSearch" @refreshLeft="refreshLeft" :tableData="tableData" @add="add" @handleEdit="handleEdit"
            @cancel="cancel" @CurrentChange="handleCurrentChange" @submit="submitClick">

            <template #search>
                <el-input maxlength="60" v-trim clearable v-model="searchForm.agencyId" style="width: 200px;"
                    placeholder="请输入渠道编号" />
                <el-input maxlength="60" v-trim clearable v-model="searchForm.name" style="width: 200px;"
                    placeholder="请输入渠道名称" />
            </template>
            <template #CustomButton>
                <el-button type="success" @click="getItmeLiet()">
                  报备部中心渠道管理
                </el-button>
            </template>
            <template #operation="{ scope }">
                <el-button v-if="scope.row.status === '停用' && IsPermission(route, 'STAET_LIST')" type="primary"
                    @click="isOpenHandle(scope.row, 1)" size="small">启用</el-button>
                <el-button v-if="scope.row.status === '启用' && IsPermission(route, 'STAET_LIST')" type="danger"
                    @click="isOpenHandle(scope.row, 2)" size="small">停用</el-button>
            </template>
            <template #status="item">
                <el-switch :disabled="!IsPermission(route, 'STAET_LIST')" v-model="item.scope.row.status"
                    active-value="ENABLE" inactive-value="DISABLE" active-color="#13ce66" inactive-color="#ff4949"
                    @click="handleBeforeChange(item.scope.row.status, item.scope.row)">
                </el-switch>
            </template>
            <template #fieldList>
                <div style="padding: 0 0 30px 0;text-align: right;">
                    <el-button type="success" icon="Plus" @click="addBtn" style="margin-bottom: 10px;" v-show="typeOption=='add'||typeOption=='edit'">
                        添加
                    </el-button>
                    <el-table :data="dataForm.configSetInfos" :border="true">
                        <!-- <el-table-column type="index" header-align="center" align="center" width="50"></el-table-column> -->
                        <el-table-column label="协议名称">
                            <template v-slot="scope">
                                <div class="input-wrap">
                                    <el-form-item prop="agreementName">
                                        <el-input maxlength="60" v-trim clearable v-model="scope.row.agreementName"
                                            placeholder="协议名称"></el-input>
                                    </el-form-item>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="协议编号">
                            <template v-slot="scope">
                                <div class="input-wrap">
                                    <el-form-item prop="agreementId">
                                        <el-input maxlength="60" v-trim clearable v-model="scope.row.agreementId"
                                            placeholder="协议编号"></el-input>
                                    </el-form-item>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="有效期">
                            <template v-slot="scope">
                                <div class="input-wrap">
                                    <el-form-item prop="termOfValidity">
                                        <el-input maxlength="60" v-trim clearable v-model="scope.row.termOfValidity"
                                            placeholder="有效期"></el-input>
                                    </el-form-item>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="协议附件">
                            <template v-slot="scope">
                                <el-upload ref="upload" :file-list="scope.row.fileList" style="padding-top: 9px;"
                                    :limit="1" :on-exceed="handleExceed" class="upload-demo" :data="data"
                                    :action="uploadUrl" @success="onSuccess($event, scope.row)">
                                    <el-button type="primary" icon="upload">
                                        上传附件
                                    </el-button>
                                </el-upload>
                            </template>
                        </el-table-column>
                        <el-table-column label="对公账户">
                            <template v-slot="scope">
                                <div class="input-wrap">
                                    <el-form-item prop="corporateAccount">
                                        <el-input maxlength="60" v-trim clearable v-model="scope.row.corporateAccount"
                                            placeholder="对公账户"></el-input>
                                    </el-form-item>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="商户号">
                            <template v-slot="scope">
                                <div class="input-wrap">
                                    <el-form-item prop="merchantId">
                                        <el-input maxlength="60" v-trim clearable v-model="scope.row.merchantId"
                                            placeholder="商户号"></el-input>
                                    </el-form-item>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="开户行">
                            <template v-slot="scope">
                                <div class="input-wrap">
                                    <el-form-item prop="openingBank">
                                        <el-input maxlength="60" v-trim clearable v-model="scope.row.openingBank"
                                            placeholder="开户行"></el-input>
                                    </el-form-item>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="70" v-if="typeOption=='add'||typeOption=='edit'">
                            <template v-slot="scope">
                                <el-button class="op-btn" type="danger" @click="deleteHandle(scope.row, scope.$index)">
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </template>
        </crud-template>

        <el-dialog title="报备部中心渠道管理" v-model="vShowDoalog">
            <crud-template ref="crudRefTwo" :home-data="zxqdFind" @submit="itemAdd" @handleEdit="itemEdit" @add="Adds"
                @CurrentChange="handleCurrentChangeTwo" :searchForm="searchForm2" @handleDelete="itemDelete"
                :tableData="tableItemData" @btnSearch="btnSearch2" @refreshLeft="refreshLeft2">
            <template #search>
                <el-input maxlength="60" v-trim clearable v-model="searchForm2.id" style="width: 200px;"
                    placeholder="请输入渠道编号" />
                <el-input maxlength="60" v-trim clearable v-model="searchForm2.name" style="width: 200px;"
                    placeholder="请输入渠道名称" />
            </template>
            </crud-template>
        </el-dialog>
    </div>
</template>

<!-- 渠道配置 -->
<script lang="ts" setup>
// @ts-ignore crudFrom模板
import CrudTemplate from "@/crud/index.vue";
import { computed, ref, toRaw, onMounted } from "vue";
import { ElMessage, UploadProps, UploadRawFile, genFileId } from "element-plus";
import { useDebounce } from "@/utils/utils";
import { addAgencyApi, updatAgencyeApi, queryAgencyApi, openAgencyApi } from "@/api/system/branch";
import BaseService from "@/utils/baseService";
import { IObject } from "@/types/interface";
import $storeinitData from "@/store/initData"; //引入tab vuex
import { useRoute } from 'vue-router';
import { IsPermission } from "@/router/routerUtil";
import { getZxqdFindConfig } from "./data.js";
//或取路由传入过来的对象数据
const route = useRoute();
const crudRef = ref();
const zxqdFind = ref(getZxqdFindConfig(route));;
const crudRefTwo = ref();
const itemStart = ref(true);
const vShowDoalog = ref(false);
const searchForm = ref({
    name: "",
    agencyId: "",
});
const searchForm2 = ref({
    id:"",
    name:""
});
const initItem = {
    name: "",
    agencyId: "",
    corporateAccount: "",
    merchantId: "",
    openingBank: "",
    status: 1,
    address: "",
    tel: ""
};
//订单阶段
const AGENCY_TYPE = computed(() => {
    return $storeinitData.state.dictData['AGENCY_TYPE'] || []
})
// console.log(AGENCY_TYPE, '--------------------------');

const addForm: any = ref(initItem);
const tableData = ref([]);
const tableItemData = ref([]);
const getCenterAgencyIdList = ref([]);
const typeOption = ref("");
let formLabelWidth = '150px';
const itemStartValue = ref("1")
//新增
const itemAdd = (data: any) => {
    request(data, itemStartValue.value)
}

const Adds = () => {
    // console.log(zxqdFind.value.field[0].form);
    zxqdFind.value.field[0].form.hideEdit = false;
    itemStartValue.value = 1
}

//表单编辑按钮
function itemEdit(idx: any, row: any) {
    // console.log("我是编辑事件", idx, row);
    zxqdFind.value.field[0].form.hideEdit = true;
    // request(row, 2)
    itemStartValue.value = 2
}

//表单编辑按钮
function itemDelete(idx: any, row: any) {
    // console.log("删除事件", idx, row);
    BaseService.postN('/userw/centerAgency/delete', row).then((res: any) => {
        if (res && res.code === 0) {
            getItmeLiet()
            crudRefTwo.value.reset();
            crudRefTwo.value.dialogFormVisible = false;
        } else {
            ElMessage.error(res.message)
        }
    })
}
function handleCurrentChangeTwo(val: number) {
    zxqdFind.value.paging.currentPage = val;
    getItmeLiet();
}
const request = (data: any, type: any) => {
    data.optType = type //操作类型 1新增 2修改
    BaseService.postN('/userw/centerAgency/addOrUpDate', data).then((res: any) => {
        if (res && res.code === 0) {
            getItmeLiet()
            crudRefTwo.value.reset();
            crudRefTwo.value.dialogFormVisible = false;
            ElMessage.success("操作成功")
        } else {
          ElMessage.error(res.message)
        }
    })
}
const getItmeLiet = () => {
    vShowDoalog.value = true
    if (crudRefTwo.value) {
        crudRefTwo.value.tableLoding = true;
    }
    let params: any = {
        id: searchForm2.value.id,
        name: searchForm2.value.name,
        pageNo: zxqdFind.value.paging.currentPage,
        pageSize: zxqdFind.value.paging.pageSize,
    }

    BaseService.postN('/userw/centerAgency/page', params).then((res: any) => {
        // console.log(res, 'res')
        if (res && res.code === 0) {
            let bizContent = res.data
            let data = bizContent.result || [];
            data.forEach((item) => {
                if (item.models) item.models.forEach((i) => {
                    if (i.agreementAnnex) i.fileList = [{ name: i.agreementAnnex }]
                })
            })
            // console.log("bizContent12222", data)
            tableItemData.value = data;
            crudRefTwo.value.tableLoding = false;
            zxqdFind.value.paging.total = bizContent.totalCount;
        } else {
            crudRefTwo.value.tableLoding = false;
            ElMessage.error(res.message)
        }
    })
}

//表单数据配置
const field = ref({
    tabSize: "small", //Table 的尺寸 large / default /small (默认default)
    searchShow: IsPermission(route, 'QUERY_BASE'), //是否显示搜索模块(默认false)
    border: true, //是否添加边框(默认false)
    dialogCustom: false, //自定义Dialog (默认false)
    dialogFooter: false, //隐藏弹窗页脚显示 (默认false)
    dialogWidth: "70%", //dialog宽度 (默认40%)
    dialogInfoWidth: "70%",
    crudShow: true, //是否显示CURD操作栏 (默认true)
    crudChildShow: true, //是否显示CURD子操作栏 (默认true)
    paginStart: true, //是否显示分页查询 (默认false)
    titleDialog: "", //table 标题
    dataListLoading: false,
    paging: {
        pageSize: 10,
        currentPage: 1,
        total: 0
    },
    crud: {
        add: IsPermission(route, 'ADD_BASE'),
        edit: false,
        delete: false,
        derive: false,
        search: false,
        refresh: false,
    },
    searchOperation: {
        isDownload: false,
        isAdd: false,
        isTransferMachine: false,
    },
    tableSize: -1,
    operateShow: true, //是否为表格添加操作栏(默认true)
    operateTitle: "操作", //操作栏标题(默认为"")
    operateFixed: true, //操作栏是否固定(默认false)
    operateWidth: "160", //操作栏宽度
    operate: {
        edit: IsPermission(route, 'EDIT_LIST'), //是否编辑(默认true)
        info: IsPermission(route, 'INFO_LIST'), //是否编辑(默认true)
        delete: false, //是否删除(默认true)
        announcement: false, // 公告
        remark: false, // 详情
        forbidden: false, // 禁用
        enable: false, // 启用
        authorization: false, // 授权
        cancel: false, // 取消订单
        writeOff: false, // 注销
        make: false, // 补缴
    },
    extend: [
        {
            label: "序号",
            type: "index", //类型:selection,index,expand
            width: "50px", //表头宽度
        },
    ],
    field: [
        {
            prop: "issuerId",
            label: "发行方编号",
            width: "80px"
        },
        {
            prop: "name",
            label: "渠道名称",
            width: "200px",
            form: {
                width: '45%',
                formLabelWidth: formLabelWidth,
                type: 'input',
                required: true,
            }
        },
        {
            prop: "agencyId",
            label: "渠道编号",
            width: "100px",
            form: {
                width: '45%',
                formLabelWidth: formLabelWidth,
                type: 'input',
                required: true,
                disabled: false
            }
        },
        {
            prop: "mapAgencyId",
            label: "中心渠道编号",
            width: "120px",
            listData: getCenterAgencyIdList,
            form: {
                width: '45%',
                formLabelWidth: formLabelWidth,
                type: 'select',
                required: true,
                listData: getCenterAgencyIdList
            }
        },
        {
            prop: "type",
            label: "合作机构类别",
            width: "100px",
            listData: AGENCY_TYPE,
            form: {
                width: '45%',
                formLabelWidth: formLabelWidth,
                type: 'select',
                required: true,
                listData: AGENCY_TYPE
            }
        },
        {
            prop: "contact",
            label: "联系人姓名",
            form: {
                width: '45%',
                formLabelWidth: formLabelWidth,
                type: 'input',
            }
        }, {
            prop: "tel",
            label: "联系电话",
            form: {
                width: '45%',
                formLabelWidth: formLabelWidth,
                type: 'input'
            }
        }, {
            hide: true,
            prop: "taxPayerCode",
            label: "纳税人识别号",
            form: {
                width: '45%',
                formLabelWidth: formLabelWidth,
                type: 'input',
            }
        }, {
            hide: true,
            prop: "creditCode",
            label: "统一社会信用代码",
            form: {
                width: '45%',
                formLabelWidth: formLabelWidth,
                type: 'input',
            }
        }, {
            hide: true,
            prop: "accountId",
            label: "记账渠道号",
            form: {
                width: '45%',
                formLabelWidth: formLabelWidth,
                type: 'input',
            }
        },
        {
            prop: 'address',
            label: '地址',
            form: {
                width: '45%',
                formLabelWidth: formLabelWidth,
                type: 'input',
            }
        },
        {
            prop: 'distributionTeamLeader',
            label: '市场发行组负责人',
            hide: true,
            form: {
                width: '45%',
                formLabelWidth: formLabelWidth,
                type: 'input',
            }
        },
        {
            prop: 'customerTeamLeader',
            label: '客服组负责人',
            hide: true,
            form: {
                width: '45%',
                formLabelWidth: formLabelWidth,
                type: 'input',
            }
        },
        {
            prop: 'technicalTeamLeader',
            label: '技术组负责人',
            hide: true,
            form: {
                width: '45%',
                formLabelWidth: formLabelWidth,
                type: 'input',
            }
        },
        {
            prop: 'settlementTeamLeader',
            label: '结算组负责人',
            hide: true,
            form: {
                width: '45%',
                formLabelWidth: formLabelWidth,
                type: 'input',
            }
        },
        {
            prop: 'email',
            label: 'email',
            form: {
                width: '45%',
                formLabelWidth: formLabelWidth,
                type: 'input',
            }
        },
        {
            prop: 'status',
            label: '状态',
            slotSet: true,
            slotSetName: "status",
        },
        {
            prop: "info",
            label: "备注",
            span: 3,
            form: {
                width: '95%',
                formLabelWidth: formLabelWidth,
                type: 'input',
                itemType: 'textarea',
                rows: 5
            }
        },
        {
            hide: true,
            prop: "agencyModels",
            form: {
                width: '95%',
                slotSetEdit: true,
                slotSetNameEdit: 'fieldList',
                formLabelWidth: '40px',
                slotSetInfo: true,
                slotSetNameInfo: 'fieldList',
            }
        },
        {
            prop: "insertTime",
            label: "创建时间",
            width: "150px",
            funRuleStarts: true,
            funRule: (val: any) => {
                if (val) {
                    return val.replaceAll('T', ' ')
                }
                return val
            },
        }
    ]
});
// 搜索按钮
function btnSearch() {
    field.value.paging.currentPage = 1;
    getList();
}

function btnSearch2() {
  zxqdFind.value.paging.currentPage = 1
  getItmeLiet()
}
// 搜索重置
function refreshLeft() {
    searchForm.value = {
        name: "",
        agencyId: ""
    }
    field.value.paging.currentPage = 1;
    getList();
}
function refreshLeft2() {
    searchForm2.value = {
    id: '', 
    name:'',
  }
    zxqdFind.value.paging.currentPage = 1
    getItmeLiet()
}
function getCenterAgencyId() {
    //获取中心网点编号信息 /userw/agency/getCenterAgencyId
    BaseService.postN('/userw/centerAgency/getCenterAgencyId', {

    }).then((res: any) => {
        // console.log(res, 'resresres');
        let bizContent = res.data
        getCenterAgencyIdList.value = bizContent.map((item) => {
            return { label: item.centerAgencyName, value: item.centerAgencyId }
        })
    })
}
function add() {
    typeOption.value = "add";
    dataForm.value.configSetInfos = []
    field.value.field.forEach(item => {
        if (item.prop === 'agencyId') {
            item.form.disabled = false
        }
    })
    BaseService.postN('/userw/agency/getAgencyId', {}).then((res: any) => {
        if (res && res.code === 0) {
            let bizContent = res.data
            crudRef.value.form.agencyId = bizContent
        } else {
            ElMessage.error(res.message)
        }
    })
}
//表单编辑按钮
function handleEdit(idx: any, row: any) {
    dataForm.value.configSetInfos = row.models ?? []
    const data = toRaw(row);

    typeOption.value = "edit";
    addForm.value = {
        ...data
    }
    // console.log(data, '===');
    // Object.assign(addForm.value,data)
    crudRef.value.title = "编辑";
    crudRef.value.dialogFormVisible = true;
    field.value.field.forEach(item => {
        if (item.prop === 'agencyId') {
            item.form.disabled = true
        }
    })
}



function handleCurrentChange(val: number) {
    field.value.paging.currentPage = val;
    getList();
}

//切换按钮 ENABLE 启用 DISABLE 停用
function handleBeforeChange(value, arg1) {
    // arg1.status == 1 ? 1 : 2
    // console.log(value, arg1);
    
    BaseService.postN('/userw/agency/agencyenable', {
        agencyId: arg1.agencyId,
        status:value
    }).then((res: any) => {
        if (res && res.code === 0) {
            if (value == 'ENABLE') {
                ElMessage.success("启用成功");
            } else {
                ElMessage.error("禁用成功");
            }
        } else {
            ElMessage.error(res.message);
        }
    });
}

// 取消
function cancel() {
    addForm.value = JSON.parse(JSON.stringify(initItem)); //清空数据
    crudRef.value.reset();
    crudRef.value.dialogFormVisible = false;
    typeOption.value = ""
    crudRef.value.title = "";
}
// 提交
function submitClick(data: any) {
    data.agencyModels = dataForm.value.configSetInfos
    let api = '/userw/agency/agencyinsert';
    if (typeOption.value === 'edit') {
        api = '/userw/agency/agencyupdate';
    }
    BaseService.postN(api, data).then((res: any) => {
        if (res && res.code === 0) {
            ElMessage.success("操作成功");
            getList();
            cancel();
        } else {
            ElMessage.error(res.message)
        }
    })
}
const submitHandle = useDebounce(submitClick);
function getList() {
    //itemStart.value = false;
    crudRef.value.tableLoding = true;
    let params: any = {
        methods: "page",
        pageNo: field.value.paging.currentPage,
        pageSize: field.value.paging.pageSize,
    }
    let searchFormList = { ...searchForm.value }
    for (let key in searchFormList) {
        if (searchFormList[key]) {
            params[key] = searchFormList[key]
        }
    }
    BaseService.postN('/userw/agency/agencyquery', params).then((res: any) => {
        // console.log(res, 'res')
        if (res && res.code === 0) {
            let bizContent = res.data
            let data = bizContent.result || [];
            data.forEach((item) => {
                if (item.models) item.models.forEach((i) => {
                    if (i.agreementAnnex) i.fileList = [{ name: i.agreementAnnex }]
                })
            })
            // console.log("bizContent12222", data)
            tableData.value = data;
            crudRef.value.tableLoding = false;
            field.value.paging.total = bizContent.totalCount;
        } else {
            crudRef.value.tableLoding = false;
            ElMessage.error(res.message)
        }
    })
}
// 启用、禁用
function isOpenHandle(row: IObject, type: number) {
    // console.log(type);
    
    // type 1是启用 2是禁用 
    BaseService.postN('/userw/agency/agencyenable', {
        agencyId: row.agencyId,
        status: type == 1 ? 'ENABLE' : 'DISABLE'
    }).then((res: any) => {
        if (res && res.code === 0) {
            getList();
            ElMessage.success("操作成功");
        } else {
            ElMessage.error(res.message)
        }
    })

}
// 字段列表
const dataForm = ref<{ id?: string; configSetInfos?: any }>({
    configSetInfos: [],
})

// 添加
const addBtn = () => {
    dataForm.value.configSetInfos.push({
        corporateAccount: '',
        merchantId: '',
        openingBank: '',
        agreementName: '',
        agreementId: '',
        termOfValidity: '',
        agreementAnnex: ''
    })
}

// 删除
const deleteHandle = (item, index) => {
    dataForm.value.configSetInfos.splice(index, 1)
}

// 附件上传
const data = { bucket: "" };
const uploadUrl = "/minIo/upload"
const upload = ref()
const url = import.meta.env.VITE_APP_UPLOAD_URL
//覆盖替换上一个文件
const handleExceed: UploadProps['onExceed'] = (files) => {
    ElMessage.error('只能上传一条附件！')
}
function onSuccess(response: any, row: any) {
    // import.meta.env.VITE_APP_UPLOAD_URL + 
    // row.agreementAnnex =  response.data.ossFilePath
    row.agreementAnnex = response.data.originalFileName
}

onMounted(() => {
    getList();
    getCenterAgencyId();
})

</script>
<style lang="scss" scoped>
.input-wrap {
    .el-form-item {
        margin-bottom: 0;
    }
}
</style>