package com.chinaweal.aiccs.aiccs.abnormal.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.abnormal.entity.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAbnList;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSBizSpeList;
import com.chinaweal.aiccs.aiccs.abnormal.entity.Toincludeabn;
import com.chinaweal.aiccs.aiccs.abnormal.entity.vo.TSBizSpeListVO;
import com.chinaweal.aiccs.aiccs.abnormal.service.*;
import com.chinaweal.aiccs.aiccs.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.entbase.entity.TREntPriseType;
import com.chinaweal.aiccs.aiccs.entbase.service.TREntPriseTypeService;
import com.chinaweal.aiccs.aiccs.market.entity.TSUsualInspect;
import com.chinaweal.aiccs.aiccs.market.service.ITSUsualInspectService;
import com.chinaweal.aiccs.aiccs.query.entity.TSEntBaseQuery;
import com.chinaweal.aiccs.aiccs.system.entity.TRBaseCode;
import com.chinaweal.aiccs.aiccs.system.service.TRBaseCodeService;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.ConstantsUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.crgs.entbase.service.TCompanyDetailsService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.page.PageRequestDto;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import com.chinaweal.youfool.framework.springboot.util.AssertUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021/1/26 15:27
 **/
@Api("ExptListController")
@RestController
@RequestMapping("/exptList")
public class ExptListController extends BaseController {
    @Autowired
    private TSBizSpeListService tsBizSpeListService;
    @Autowired
    private TREntPriseTypeService entPriseTypeService;
    @Autowired
    private TCompanyDetailsService tCompanyDetailsService;
    @Autowired
    private TSAbnListService abnListService;
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private TRBaseCodeService baseCodeService;
    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private ToincludeabnService toincludeabnService;
    @Autowired
    private IGzaiccodeService gzaiccodeService;
    @Resource
    private ITSUsualInspectService iTSUsualInspectService;

    /**
     * 列入经营异常名录通用查询
     */
    @RequestMapping(value = "/abnormalListSearch.do")
    public RestResult<?> abnormalListSearch(HttpServletRequest request, TSEntBaseQuery tsEntBaseQueryModel,
                                            String fullCode, String subEntType, String marketName,
                                            String industryName, String importAreaName, int rows, int page) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) throw new BusinessException("登录超时，请重新登录");
//        if(!WebUtil.isEmpty(aicUser.getRegionID())){//只查询本机构监管的主体
//            tsEntBaseQueryModel.setLocalAdm(aicUser.getRegionID());
//        }

        int count = 0;
        //判断企业类型，进行字符串拼接
        if (StringUtils.isNotBlank(subEntType)) {
            String[] subEntTypes = subEntType.split(",");
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < subEntTypes.length; i++) {
                sb.append("'" + subEntTypes[i] + "'");
                if ((subEntTypes.length - 1) != count) {
                    sb.append(",");
                }
                count++;
            }
            count = 0; /*拼接不同的字符串却用同个count作比较，应清零*/
            tsEntBaseQueryModel.setTypeList(sb.toString());
        }

        //重点行业的字符串拼接
        if (StringUtils.isNotBlank(industryName)) {
            String[] industryNames = industryName.split(",");
            StringBuffer sb1 = new StringBuffer();
            for (int i = 0; i < industryNames.length; i++) {
                sb1.append("'" + industryNames[i] + "'");
                if ((industryNames.length - 1) != count) {
                    sb1.append(",");
                }
                count++;
            }
            count = 0; /*拼接不同的字符串却用同个count作比较，应清零*/
            tsEntBaseQueryModel.setIndustryName(sb1.toString());
        }

        //所属市场的字符串拼接
        if (StringUtils.isNotBlank(marketName)) {
            String[] marketNames = marketName.split(",");
            StringBuffer sb1 = new StringBuffer();
            for (int i = 0; i < marketNames.length; i++) {
                sb1.append("'" + marketNames[i] + "'");
                if ((marketNames.length - 1) != count) {
                    sb1.append(",");
                }
                count++;
            }
            count = 0; /*拼接不同的字符串却用同个count作比较，应清零*/
            tsEntBaseQueryModel.setMarketName(sb1.toString());
        }

        //重点区域的字符串拼接
        if (StringUtils.isNotBlank(importAreaName)) {
            String[] importAreaNames = importAreaName.split(",");
            StringBuffer sb2 = new StringBuffer();
            for (int i = 0; i < importAreaNames.length; i++) {
                sb2.append("'" + importAreaNames[i] + "'");
                if ((importAreaNames.length - 1) != count) {
                    sb2.append(",");
                }
                count++;
            }
            tsEntBaseQueryModel.setImportAreaName(sb2.toString());
        }
        //截取字符串
        if (StringUtils.isNotBlank(fullCode)) {
            //行业门类
            String charCode = fullCode.substring(0, 1);//获取前面一个字符 ,到数据库中查询
            String industryCo = fullCode.substring(1, fullCode.length());
            tsEntBaseQueryModel.setIndustryPhy(charCode);
            tsEntBaseQueryModel.setIndustryCo(industryCo);
        }
        IPage<TSEntBaseQuery> tsEntBaseQueryModelDataGrid = tsBizSpeListService.abnormalListByPage(new Page<>(page, rows), tsEntBaseQueryModel);
        return RestResult.ok(tsEntBaseQueryModelDataGrid);
    }

//    /**
//     * 获取通过业务号id获取所有异常名录
//     * @param bizSeqId 业务号
//     * @return 异常名录
//     * @author lroyia
//     * @since 2021年2月7日 16:17:03
//     */
//    @RequestMapping("list_by_bizseqid")
//    public RestResult<List<TSBizSpeList>> getBizSpeListByBizSeqId(String bizSeqId){
//        AssertUtils.isNotBlank(bizSeqId);
//        List<TSBizSpeList> list = tsBizSpeListService.list(new LambdaQueryWrapper<TSBizSpeList>().eq(TSBizSpeList::getBizseq, bizSeqId));
//        list.forEach(each -> {
//            TREntPriseType type = entPriseTypeService.getEntPriseTypeFromCache(each.getEnttype());
//            if(type != null){
//                each.setEntTypeName(type.getDisplayvalue());
//            }
//        });
//        return RestResult.ok(list);
//    }

    /**
     * 获取通过业务号id获取所有异常名录
     *
     * @param bizSeqId 业务号
     * @return 异常名录
     * @author Lee
     */
    @RequestMapping("list_by_bizseqid")
    public RestResult<List<TSBizSpeListVO>> getBizSpeListByBizSeqId(String bizSeqId) throws Exception {
        AssertUtils.isNotBlank(bizSeqId);
        List<TSBizSpeList> list = tsBizSpeListService.list(new LambdaQueryWrapper<TSBizSpeList>()
                .eq(TSBizSpeList::getBizseq, bizSeqId).ne(TSBizSpeList::getIsRemove,"1"));
        List<TSBizSpeListVO> listVOList = new ArrayList<>();
        list.forEach(each -> {
            TSBizSpeListVO listVO = new TSBizSpeListVO();
            BeanUtils.copyProperties(each, listVO);
            listVOList.add(listVO);
        });
        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
        listVOList.forEach(each -> {
            EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, each.getPripid()));
            //经营地址
            each.setAddress(StringUtils.isNotEmpty(eBaseinfo.getDom())? eBaseinfo.getDom():eBaseinfo.getOploc());
            each.setRegstate(eBaseinfo.getRegstate());//登记状态
            TRBaseCode code = codeMap.get(eBaseinfo.getRegstate());
            if(code != null) {
                each.setRegstateCn(code.getName());//登记状态str
            }
            each.setEstDate(eBaseinfo.getEstdate());//成立日期
            each.setLerepname(eBaseinfo.getLerep());//法定代表人
            if (eBaseinfo.getEnttypeCn() == null) {
                TREntPriseType type = entPriseTypeService.getEntPriseTypeFromCache(each.getEnttype());
                if (type != null) {
                    each.setEntTypeName(type.getDisplayvalue());
                }
            }else {
                each.setEntTypeName(eBaseinfo.getEnttypeCn());
            }
            each.setDecorgCn(gzaiccodeService.getNameByCode(each.getDecorg()));
        });
        return RestResult.ok(listVOList);
    }

    /**
     * 列异业务获取在办名单--分页
     * @param pageRequestDto  分页参数
     * @param request
     * @return
     */
    @PostMapping("getBizSpeListPage")
    public RestResult<?> getBizSpeListPage(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request){
        AssertUtils.isNotNull(pageRequestDto,pageRequestDto.getCustomParamMap());
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
        String bizseq = StringUtils.tranObject(customParamMap.get("bizseq"));
        if(StringUtils.isEmpty(bizseq)){
            return RestResult.error(ResultCode.PARAM_IS_BLANK);
        }

        String dataFromId = null;
        IPage<TSBizSpeListVO> page = tsBizSpeListService.selectBizSpeListPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()),customParamMap);
        // 封装企业基本信息
        if(CollectionUtils.isNotEmpty(page.getRecords())){
            Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
            for (TSBizSpeListVO record : page.getRecords()) {
                EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, record.getPripid()));
                //经营地址
                record.setAddress(StringUtils.isNotEmpty(eBaseinfo.getDom())? eBaseinfo.getDom():eBaseinfo.getOploc());
                record.setRegstate(eBaseinfo.getRegstate());//登记状态
                TRBaseCode code = codeMap.get(eBaseinfo.getRegstate());
                if(code != null) {
                    record.setRegstateCn(code.getName());//登记状态str
                }
                record.setEstDate(eBaseinfo.getEstdate());//成立日期
                record.setLerepname(eBaseinfo.getLerep());//法定代表人
                if (eBaseinfo.getEnttypeCn() == null) {
                    TREntPriseType type = entPriseTypeService.getEntPriseTypeFromCache(record.getEnttype());
                    if (type != null) {
                        record.setEntTypeName(type.getDisplayvalue());
                    }
                }else {
                    record.setEntTypeName(eBaseinfo.getEnttypeCn());
                }
                record.setDecorgCn(gzaiccodeService.getNameByCode(record.getDecorg()));
                if (StringUtils.isNotEmpty(record.getToIncludeId())) {
                    // 线索主键
                    Toincludeabn toincludeabn = toincludeabnService.getById(record.getToIncludeId());
                    record.setDataFromId(toincludeabn.getDataFromId());
                    record.setDataFrom(toincludeabn.getDataFrom());
                    record.setRegEntryUserName(toincludeabn.getRegEntryUserName());
                    dataFromId = toincludeabn.getDataFromId();
                }
            }
            if(dataFromId != null){
                TSUsualInspect tsUsualInspect = iTSUsualInspectService.getById(dataFromId);
                if(tsUsualInspect != null && StringUtils.isNotEmpty(tsUsualInspect.getCheckAddress())) {
                    page.getRecords().get(0).setCheckAddress(tsUsualInspect.getCheckAddress());
                }
            }
        }
        return RestResult.ok(page);
    }

    @RequestMapping("list_by_bizseqidAndEntName")
    public RestResult<List<TSBizSpeListVO>> getBizSpeListByBizSeqIdAndEntName(String bizSeqId,String entName) throws Exception {
        AssertUtils.isNotBlank(bizSeqId);
        List<TSBizSpeList> list = tsBizSpeListService.list(new LambdaQueryWrapper<TSBizSpeList>().eq(TSBizSpeList::getBizseq, bizSeqId)
                .eq(TSBizSpeList::getIsRemove,"0")
                .like(StringUtils.isNotBlank(entName),TSBizSpeList::getEntname,entName));
        List<TSBizSpeListVO> listVOList = new ArrayList<>();
        list.forEach(each -> {
            TSBizSpeListVO listVO = new TSBizSpeListVO();
            BeanUtils.copyProperties(each, listVO);
            listVOList.add(listVO);
        });
        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
        listVOList.forEach(each -> {
            EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, each.getPripid()));
            //经营地址
            if ("9910".equals(each.getEnttype())) {//个体户地址暂存 oploc字段
                each.setAddress(eBaseinfo.getOploc());
            } else {
                each.setAddress(eBaseinfo.getDom());
            }
            each.setRegstate(eBaseinfo.getRegstate());//登记状态
            TRBaseCode code = codeMap.get(eBaseinfo.getRegstate());
            if(code != null) {
                each.setRegstateCn(code.getName());//登记状态str
            }
            each.setEstDate(eBaseinfo.getEstdate());//成立日期
            each.setLerepname(eBaseinfo.getName());//法定代表人
            if (eBaseinfo.getEnttypeCn() == null) {
                TREntPriseType type = entPriseTypeService.getEntPriseTypeFromCache(each.getEnttype());
                if (type != null) {
                    each.setEntTypeName(type.getDisplayvalue());
                }
            }
            each.setEntTypeName(eBaseinfo.getEnttypeCn());
        });
        return RestResult.ok(listVOList);
    }

    /**
     * 通过业务id删除拟列入主体
     *
     * @param spelistids 业务号
     * @param removeReason 剔除原因
     * @return 删除成功或失败
     * @author Lee
     */
    @Transactional
    @ApiOperation(value = "通过业务号id删除拟列入主体")
    @RequestMapping("remove_by_spelistid")
    public RestResult<?> removeBySpelistid(String spelistids,String removeReason,String bizseq, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        if (user == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        AssertUtils.isNotBlank(spelistids,removeReason,bizseq);
        String[] spelistidArray = spelistids.split(Constant.SEMICOLON);//要改
        // 物理删改逻辑删
        boolean isDelete = false;
        LocalDateTime now = LocalDateTime.now();
        for (String spelistid : spelistidArray) {
            TSBizSpeList speList = new TSBizSpeList();
            speList.setSpelistid(spelistid);
            speList.setIsRemove("1");
            speList.setRemoveReason(removeReason);
            speList.setRemoveTime(now);
            speList.setRemoveHandler(user.getName());
            isDelete = tsBizSpeListService.updateById(speList);
        }
        if(isDelete){
            // 更新待办名
            String busName = tsBizSpeListService.updateTaskBusName(bizseq);
            if(StringUtils.isEmpty(busName)){
                throw new BusinessException("更新待办名称失败");
            }
            return OK;
        }else {
            return RestResult.error(ResultCode.MYSTERIOUS_ERROR, "删除失败");
        }
    }


    /**
     * 已列入经营异常名录分页
     *
     * @param pageRequestDto 分页参数
     * @return 分页结果
     * @author lroyia
     * @since 2021年3月17日 09:55:54
     */
    @ApiOperation("已列入经营异常名录分页")
    @PostMapping("abnList/page")
    public RestResult<?> getAbnListPage(@ApiParam("分页参数") @RequestBody PageRequestDto pageRequestDto) {
        AssertUtils.isNotNull(pageRequestDto);
        pageRequestDto.checkDefault(1, 10, "abntime");
        return RestResult.ok(abnListService.defaultPaging(pageRequestDto, w -> {
            LambdaQueryWrapper<TSAbnList> wrapper = w.lambda();
            wrapper.eq(TSAbnList::getOperatestatus, Constant.TRUE_1_STR);

            Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
            if (customParamMap == null) return;
            // 三年前列入的记录，用于筛选处理信息
            String year3 = StringUtils.tranObject(customParamMap.get("year3"));
            if (StringUtils.isNotBlank(year3)) {
                wrapper.le(TSAbnList::getAbntime, LocalDate.now().minusYears(3));
            }
            // 是否是企业信息
            String isCompany = StringUtils.tranObject(customParamMap.get("3year"));
            if (StringUtils.isNotBlank(isCompany)) {
                // TODO:加上企业主体类型筛选

            }
        }, null));
    }
}
