<template>
    <div class="layout-content-wrap">
        <el-tabs class="zd-el-tabs-custom zd-el-tabs-custom__left_padding"  v-model="activeName" @tab-click="handleTabClick">
            <el-tab-pane name="all">
                <span slot="label"><span>全部</span> <el-badge :value="caseStatusNum.total" :max="99" class="item"></el-badge></span>
            </el-tab-pane>
            <el-tab-pane name="mediate">
                <span slot="label"><span>待调解</span> <el-badge :value="caseStatusNum.not" :max="99" class="item"></el-badge></span>
            </el-tab-pane>
            <el-tab-pane name="mediation">
                <span slot="label"><span>调解中</span> <el-badge :value="caseStatusNum.ing" :max="99" class="item"></el-badge></span>
            </el-tab-pane>
            <el-tab-pane name="mediated">
                <span slot="label"><span>已结束</span> <el-badge :value="caseStatusNum.end" :max="99" class="item"></el-badge></span>
            </el-tab-pane>
        </el-tabs>
        <div class="layout-tabs-content-box">
            <div class="pt-8 border-b-solid-lighter-1">
                <div class="height-30 flex-row align-items-center justify-content-between mb-24">
                    <div class="f22 color-text-primary">筛选</div>
                    <div class="flex-row align-items-center color-text-regular cursor-pointer"
                         @click="handleToggleSearch">
                        <span class="f14 pr-8">{{showSearch?'展开':'收起'}}</span>
                        <i :class="['f14 el-icon-arrow-down transform-time-default', {
                        'rotate--180': showSearch
                    }]"></i>
                    </div>
                </div>
                <el-collapse-transition>
                    <div v-show="showSearch">
                        <el-row :gutter="56">
                            <el-col :span="8">
                                <div class="flex-row-center align-items-center height-40 mb-24">
                                    <span class="tabs__search-criteria-title flex-shrink-0 pr-16">金融机构名称</span>
                                    <el-input v-model.trim="queryParam.financialOrgName"
                                              clearable placeholder="请输入金融机构名称"
                                              @keydown.enter.native="handleSearch">
                                    </el-input>
                                </div>
                            </el-col>
                            <el-col :span="8">
                                <div class="flex-row-center align-items-center height-40 mb-24">
                                    <span class="tabs__search-criteria-title flex-shrink-0 pr-16">案件编号</span>
                                    <el-input v-model.trim="queryParam.caseNo"
                                              clearable placeholder="请输入案件编号"
                                              @keydown.enter.native="handleSearch">
                                    </el-input>
                                </div>
                            </el-col>
                            <el-col :span="8">
                                <div class="flex-row-center align-items-center height-40 mb-24">
                                    <span class="tabs__search-criteria-title flex-shrink-0 pr-16">金融产品类型</span>
                                    <el-select v-model="queryParam.productTypeId"
                                           clearable placeholder="请选择金融产品类型"
                                           @keydown.enter.native="handleSearch"
                                           class="width100">
                                    <el-option
                                            v-for="item in financialProductsTypeOptions"
                                            :key="item.code"
                                            :label="item.codeName"
                                            :value="item.code">
                                    </el-option>
                                </el-select>
                                </div>
                            </el-col>
                        </el-row>
                        <el-row :gutter="56">
                            <el-col :span="8">
                                <div class="flex-row-center align-items-center height-40 mb-24">
                                    <span class="tabs__search-criteria-title flex-shrink-0 pr-16">区域</span>
                                    <el-select v-model="queryParam.deptId"
                                            clearable placeholder="请选择区域"
                                            @keydown.enter.native="handleSearch"
                                            :disabled="deptDisabled"
                                            class="width100">
                                        <el-option
                                                v-for="item in departmentOptions"
                                                :key="item.id"
                                                :label="item.name"
                                                :value="item.id">
                                        </el-option>
                                    </el-select>
                                </div>
                            </el-col>
                            <el-col :span="8">
                                <div class="flex-row-center align-items-center height-40 mb-24">
                                    <span class="tabs__search-criteria-title flex-shrink-0 pr-16">债务人姓名</span>
                                    <el-input v-model.trim="queryParam.creditorName"
                                              clearable placeholder="请输入债务人姓名"
                                              @keydown.enter.native="handleSearch">
                                    </el-input>
                                </div>
                            </el-col>
                            <el-col :span="8">
                                <div class="flex-row-center align-items-center height-40 mb-24">
                                    <span class="tabs__search-criteria-title flex-shrink-0 pr-16">债务人电话</span>
                                    <el-input v-model.trim="queryParam.creditorPhone"
                                              clearable placeholder="请输入债务人电话"
                                              @keydown.enter.native="handleSearch"
                                              maxlength="11"
                                              >
                                    </el-input>
                                </div>
                            </el-col>
                        </el-row>
                        <el-row :gutter="56" v-if="caseStatusShow">
                            <el-col :span="8">
                                <div class="flex-row-center align-items-center height-40 mb-24">
                                    <span class="tabs__search-criteria-title flex-shrink-0 pr-16">案件状态</span>
                                    <el-select v-model="queryParam.resultStatus"
                                            clearable placeholder="请选择案件状态"
                                            @keydown.enter.native="handleSearch"
                                            :disabled="deptDisabled"
                                            class="width100">
                                        <el-option
                                                v-for="item in caseStatusData"
                                                :key="item.code"
                                                :label="item.desc"
                                                :value="item.code">
                                        </el-option>
                                    </el-select>
                                </div>
                            </el-col>
                        </el-row>
                        <el-row :gutter="56">
                            <el-col :span="18">
                                <div class="flex-row align-items-center height-40 mb-24">
                                    <span class="tabs__search-criteria-title flex-shrink-0 pr-16">创建时间</span>
                                    <span :class="['f14 pr-24 cursor-pointer', i === 0 ? 'pl-8' : '',
                                    activeUsage === item ?'color-primary' : 'color-text-regular']"
                                          v-for="(item, i) in usageOption" :key="i"
                                          @click="handleClickUsage(item)">{{item}}</span>

                                    <el-date-picker
                                            v-model="queryDate"
                                            type="daterange"
                                            clearable
                                            range-separator="至"
                                            start-placeholder="开始日期"
                                            end-placeholder="结束日期"
                                            @change="handleChangeDate">
                                    </el-date-picker>
                                </div>
                            </el-col>
                            <el-col :span="4" :offset="2">
                                <div class="flex-row align-items-center justify-content-end">
                                    <el-button @click="hanldeReset">重置</el-button>
                                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                                </div>
                            </el-col>
                        </el-row>
                    </div>
                </el-collapse-transition>
            </div>
            <!-- table -->
            <div class="pt-8">
                <div class="height-56 flex-row align-items-center justify-content-between">
                    <div class="f22 color-text-primary">案件列表</div>
                    <div class="flex-row">
                        <el-button size="small" @click="handleImport">导入</el-button>
                        <el-button size="small" @click="handleBatchDelete">删除</el-button>
                        <el-button size="small" @click="handleAddForm">新增</el-button>
                        <el-button size="small" type="primary" @click="handleCaseAllocation">案件分配</el-button>
                    </div>
                </div>
                
                <div >
                    <el-table :data="tableData" :height="`${contentHeight}`" 
                    @selection-change="handleSelectionChange"
                    >
                        <el-table-column
                            type="selection"
                            width="55" :selectable="checkSelectable">
                        </el-table-column>

                        <el-table-column
                            v-for="(item, i) in tableHead"
                            :key="i"
                            :prop="item.prop"
                            :label="item.label"
                            :show-overflow-tooltip="item.showOverflowTooltip"
                            :width="item.width"
                            :sortable="item.sortable"
                            :formatter="item.formatter"
                        ></el-table-column>
                        <el-table-column
                            prop="resultStatus"
                            label="案件状态"
                            show-overflow-tooltip
                            :formatter="formatResultStatusEnum"
                            v-if="caseStatusShow"
                            >
                        </el-table-column>
                        <el-table-column  label="操作" width="150">
                            <template slot-scope="scope">
                                <div class="flex-row align-items-center">
                                    <el-button size="mini" @click="handleEdit(scope)">编辑</el-button>
                                    <div v-if="scope.row.caseStatus == 0" class="f12 cursor-pointer color-text-regular ml-16" @click="handleDelete(scope)">删除</div>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                
                <div class="text-center pt-16">
                    <el-pagination
                        @size-change="getCaseInfoList"
                        @current-change="getCaseInfoList"
                        :current-page="queryParam.current"
                        :page-size="queryParam.size"
                        layout="total, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                </div>

            </div>
        </div>
        <!-- 导入 -->
        <importCaseDialog v-if="importCaseDialog" :importCaseDialog.sync="importCaseDialog" />
        <!-- 新增 -->
        <addCaseDialog v-if="addCaseDialog" :addCaseDialog.sync="addCaseDialog" />
        <!-- 编辑 -->
        <editCaseDrawer v-if="editCaseDrawer" :editCaseDrawer.sync="editCaseDrawer"/>
        <!-- 案件分配-->
        <caseAllocationDialog v-if="caseAllocationDialog" :caseAllocationDialog.sync="caseAllocationDialog" />
    </div>
</template>
<script>
import api from "@/services/caseManagement";
    export default {
        components: {
            importCaseDialog: () => import('./components/importCaseDialog'),//导入
            addCaseDialog: () => import('./components/addCaseDialog'),//新增
            editCaseDrawer: () => import('./components/editCaseDrawer'),//编辑
            caseAllocationDialog: () => import('./components/caseAllocationDialog'),//案件分配
        },
        data() {
            return {
                activeName:'all',
                showSearch: true,
                queryDate: '',
                activeUsage: '',
                caseStatusNum:{
                    end: 0,
                    ing: 0,
                    not: 0,
                    total:0
                },
                mediateStatusData:[],//所有案件状态枚举
                financialProductsTypeOptions:[],//金融产品类型
                departmentOptions:[],//区域
                queryParam: {
                    financialOrgName:'',//金融机构名称
                    caseNo: '',//案件编号
                    productTypeId: '',//产品类型id
                    caseStatus: '',//案件状态
                    creditorName:'',//债券人姓名
                    creditorPhone:'',//债务人手机号
                    endTime: '',//结束时间
                    beginTime:'',//开始时间
                    deptId:'',//区域id
                    current:1,
                    size:10,

                    caseName:'',//案件名称
                    dataAuthUserId:'',//当前登录用户所拥有权限的用户id
                    dataAuthDeptId:'',//当前登录用户所拥有权限的区域id
                    mediatorId:'',//调解员id
                    resultStatus:'',//结果状态

                },
                usageOption: ['今日','昨日', '近一周', '近一月', '近半年', '近一年'],
                tableHead: [
                    {
                        prop: "caseName",
                        label: "案件名称",
                        showOverflowTooltip: true,
                        formatter: this.formatTable,
                    },
                    {
                        prop: "caseNo",
                        label: "案件编号",
                        showOverflowTooltip: true,
                        formatter:this.formatTable,
                    },
                    {
                        prop: "productTypeId",
                        label: "金融产品类型",
                        showOverflowTooltip: true,
                        formatter: this.formatProductType,
                    },
                    {
                        prop: "deptId",
                        label: "归属区域",
                        showOverflowTooltip: true,
                        formatter: this.formatdeptName,
                    },
                    {
                        prop: "mediatorName",
                        label: "归属人",
                        showOverflowTooltip: true,
                         formatter:this.formatTable,
                    },
                    {
                        prop: "createAt",
                        label: "创建时间",
                        showOverflowTooltip: true,
                        formatter: this.formatTable,
                    },
                    {
                        prop: "caseStatus",
                        label: "调解状态",
                        showOverflowTooltip: true,
                        formatter: this.formatMediateStatusEnum,
                    },
                    // {
                    //     prop: "resultStatus",
                    //     label: "案件状态",
                    //     showOverflowTooltip: true,
                    //     formatter: this.formatResultStatusEnum,
                    // },
                ],
                tableData: [],
                total:0,
                uniqueSelection:[],
                caseAllocationDialog:null,//案件分配弹框
                importCaseDialog:null,//导入
                addCaseDialog:null,//新增
                editCaseDrawer:null,//编辑
                deptDisabled:false,//区域下拉设置是否可选
                caseStatusData:[],//获取调解中状态枚举
                caseStatusShow:true,//显示案件状态枚举 全部，调解中



            }
        },
        created() {
            this.getCaseCount();//获取各案件状态数量
            this.getMediateStatusEnum();//获取所有状态枚举
            this.getDict();//获取金融产品类型
            this.getDeptList();//获取区域
            // 判断当前登录人角色，如果是普通调解员，则默认展示区域且不可选择
            let identifier = this.$store.state.userinfo.identifier
            if(identifier=='mediator'){
                this.deptDisabled = true
                this.queryParam.deptId = this.$store.state.userinfo.deptId
            }else{
                this.deptDisabled = false
            }
            // this.setDateFast()
            this.getCaseStatusEnum();//获取调解中状态枚举
            this.getCaseInfoList(1)
        },
        computed:{
            // 获取抽屉drawer的内容高度
            contentHeight(){
                let oh = document.documentElement.clientHeight;
                if(this.showSearch){
                    if(this.caseStatusShow){
                        return oh-56-48-430-32
                    }else{
                        return oh-56-48-366-32
                    }
                    
                }else{
                    return oh-56-48-175-32
                }
            }  
        },
        methods: {
            checkSelectable(row) {
                if (row.caseStatus == 0) {
                    return true
                }
                else
                {
                    return false
                }
            },
            // tab切换
            handleTabClick(tab,event){
                console.log('获取e==',tab)
                if(tab.name == 'mediate'){
                    this.queryParam.caseStatus = 0//待调解
                    this.caseStatusShow = false
                }else if(tab.name == 'mediation'){
                    this.queryParam.caseStatus = 1//调解中
                    this.caseStatusShow = true
                }else if(tab.name == 'mediated'){
                    this.queryParam.caseStatus = 2//已结束
                    this.caseStatusShow = false
                }else{
                    this.queryParam.caseStatus = ''
                    this.caseStatusShow = true
                }
                this.getCaseInfoList(1)
            },
            // 导入
            handleImport(){
                this.importCaseDialog={
                    title:'导入案件',
                }
            },
            // 批量删除
            handleBatchDelete(){
                if(this.uniqueSelection.length==0){
                    this.$message.warning("请先选择你要删除的列表数据");
                    return
                }
                this.$confirm("请确定是否删除这些数据?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }).then(() => {
                    if(!this.$clickThrottle()) { return }//防止重复点击
                    
                    let data = {
                        ids:this.uniqueSelection
                    }
                    api.deleteCaseBatch(data).then((res) => {
                        
                        this.$message.success("成功");
                        this.getCaseInfoList(1)
                       
                    });
                }).catch(() => {});
            },
            // 单条删除
            handleDelete(scope){
                this.$confirm("请确定是否删除此条数据?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }).then(() => {
                    if(!this.$clickThrottle()) { return }//防止重复点击
                    api.deleteCaseInfoById(scope.row.id).then((res) => {
                        
                        this.$message.success("成功");
                        this.getCaseInfoList(1)
                       
                    });
                }).catch(() => {});
            },
            // 新增
            handleAddForm(){
                this.addCaseDialog={
                    title:'新增案件',
                }
            },
            // 案件分配
            handleCaseAllocation(){
                this.caseAllocationDialog={
                    title:'案件分配',
                }
            },
            // 编辑
            handleEdit(scope){
                this.editCaseDrawer={
                    title:'编辑案件',
                    data:scope.row,
                    currentPage:this.queryParam.current
                }
            },
            // 获取各案件状态数量
            getCaseCount(){
                api.getCaseCount({}).then(res => {
                    if (!res.code) {
                        this.caseStatusNum = res;
                    }
                })
            },
            // 获取金融产品类型
            getDict(){
                let data = {
                    type:'financial'
                }
                api.getDict(data).then(res => {
                    if (!res.code) {
                        this.financialProductsTypeOptions = res;
                    }
                })
            },
            // 获取区域
            getDeptList(){
                let data = {
                    companyId: this.$store.state.userinfo.companyId,
                    current: 1,
                    size: 500,
                }
                api.getDeptList(data).then(res => {
                    if (!res.code) {
                        this.departmentOptions = res.records;
                        
                    }
                })
            },
            // 列表数据
            getCaseInfoList(val){
                this.queryParam.current = val
                api.getCaseInfoList(this.queryParam).then(res => {
                    if (!res.code) {
                        this.tableData = res.records;
                        this.total = res.total;
                    }
                })
            },
            // 根据id获取区域名称
            formatdeptName(row, column, cellValue, index){
                let obj = this.departmentOptions.find((item) => {
                    return item.id == row.deptId
                })
                return row.deptId != null ? <div>{obj?obj.name:'-'}</div> : '-'
            },
            formatProductType(row, column, cellValue, index){
                // console.log('row',row)
                let obj = this.financialProductsTypeOptions.find((item) => {
                    return item.code == row.productTypeId
                })
                return row.productTypeId != null ? <div>{obj?obj.codeName:'-'}</div> : '-'
            },
            handleToggleSearch() {
                this.showSearch = !this.showSearch
            },
            // 重置
            hanldeReset() {
                for (let key in this.queryParam) {
                    this.queryParam[key] = ''
                }
                this.queryParam.current = 1
                this.queryParam.size = 10
                this.activeUsage = ''
                this.queryDate = ''
            },
            handleSearch() {
                this.queryParam.size = 10;
                this.queryParam.current = 1;
                this.getCaseInfoList(1)
            },
            handleClickUsage(item) {
                this.activeUsage = item
                this.setDateFast()
            },
            handleChangeDate() {
                this.activeUsage = ''
                if(this.queryDate === null) {
                    this.setDateFast()
                }else {
                    this.queryParam.beginTime = this.$util.getDayStart(this.queryDate[0])
                    this.queryParam.endTime = this.$util.getDayEnd(this.queryDate[1])
                }

            },
            setDateFast() {
                switch (this.activeUsage) {
                    case "今日":
                        let todayObj = this.$util.getToday()
                        this.queryParam.beginTime = todayObj.todayStart
                        this.queryParam.endTime = todayObj.todayEnd
                        break
                    case "昨日":
                        let yesterdayObj = this.$util.getYesterday()
                        this.queryParam.beginTime = yesterdayObj.beginTime
                        this.queryParam.endTime = yesterdayObj.endTime
                        break
                    case "近一周":
                        let rangeWeek = this.$util.getRecentWeeks()
                        this.queryParam.beginTime = rangeWeek.recentWeekStart
                        this.queryParam.endTime = rangeWeek.todayEnd
                        break
                    case "近一月":
                        let rangeMonth = this.$util.getRecentMonths()
                        this.queryParam.beginTime = rangeMonth.recentMonthStart
                        this.queryParam.endTime = rangeMonth.todayEnd
                        break
                    case "近半年":
                        let rangeMonths = this.$util.getRecentMonths(6)
                        console.log('近半年：', rangeMonths)
                        this.queryParam.beginTime = rangeMonths.recentMonthStart
                        this.queryParam.endTime = rangeMonths.todayEnd
                        break
                    case "近一年":
                        let rangeYear = this.$util.getRecentYears()
                        this.queryParam.beginTime = rangeYear.recentYearStart
                        this.queryParam.endTime = rangeYear.todayEnd
                        break
                    default:
                        this.queryParam.beginTime = ''
                        this.queryParam.endTime = ''
                        this.queryDate = ''
                        break
                }
                if(this.queryParam.beginTime && this.queryParam.endTime) {
                    this.queryDate = [this.queryParam.beginTime, this.queryParam.endTime]
                }

            },

            handleSelectionChange(val){
                console.log('获取val',val)
                this.uniqueSelection = []
                val.forEach((row)=>{
                    this.uniqueSelection.push(row.id)
                })
                console.log('uniqueSelection',this.uniqueSelection)

            },
            
            // 获取案件状态枚举-调解状态
            getMediateStatusEnum(){
                api.getMediateStatusEnum({}).then(res => {
                    if (!res.code) {
                        this.mediateStatusData = res;
                    }
                })
            },
            // 案件状态
            formatMediateStatusEnum(row, column, cellValue, index){
                // console.log('row',row)
                let className = `status-btn case-status${row.caseStatus}`
                let obj = this.mediateStatusData.find((item) => {
                    return item.code == row.caseStatus
                })
                return row.caseStatus != null ? <div class={className}>{obj.desc}</div> : '-'
                
            },

            // 获取调解中案件状态枚举
            getCaseStatusEnum(){
                api.getCaseStatusEnum({}).then(res => {
                    if (!res.code) {
                        this.caseStatusData = res;
                    }
                })
            },
            formatResultStatusEnum(row, column, cellValue, index){
                // console.log('row',row)
                let className = `status-btn result-status${row.resultStatus}`
                let obj = this.caseStatusData.find((item) => {
                    return item.code == row.resultStatus
                })
                return row.resultStatus != null ? <div class={className}>{obj.desc}</div> : '-'
                
            },
            
        }
    }
</script>
<style scoped >
.el-badge{
    top: 3px;
}
</style>