package com.chinaweal.aiccs.aiccs.revoke.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chinaweal.aiccs.aiccs.revoke.entity.Illegalact;
import com.chinaweal.aiccs.aiccs.revoke.entity.TsCase;
import com.chinaweal.aiccs.aiccs.revoke.entity.Tsbizrevlist;
import com.chinaweal.aiccs.aiccs.revoke.entity.Tswritscontent;
import com.chinaweal.aiccs.aiccs.revoke.service.CaseService;
import com.chinaweal.aiccs.aiccs.revoke.service.IllegalactService;
import com.chinaweal.aiccs.aiccs.revoke.service.TsbizrevlistService;
import com.chinaweal.aiccs.aiccs.revoke.service.TswritscontentService;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.WorkNoUtil;
import com.chinaweal.aicorg.model.AICUser;
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.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
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.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;


/**
 * <p>
 * 文书模板内容表 前端控制器
 * </p>
 *
 * @author Lee
 * @since 2021-07-14
 */
@Transactional
@RestController
@RequestMapping("/tswritscontent")
public class TswritscontentController extends BaseController {

    @Autowired
    private TswritscontentService tswritscontentService;
    @Autowired
    private CaseService caseService;
    @Autowired
    private IllegalactService illegalactService;
    @Lazy
    @Autowired
    private TsbizrevlistService tsbizrevlistService;

    /**
     *  根据业务号及文书类型获取文书模板内容
     *
     * @param tswritscontent 文书模板内容参数对象
     * @return
     */
/*    @ApiOperation("根据业务号及文书类型获取文书模板内容")
    @PostMapping("getContentsWithBizseq")
    public RestResult<?> getContentsWithBizseq(@RequestBody Tswritscontent tswritscontent){
        AssertUtils.isNotBlank(tswritscontent.getBizseq(),tswritscontent.getWritsType());
        // 先查找业务中有没有编辑保存过的文书内容，有则返回
        LambdaQueryWrapper<Tswritscontent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Tswritscontent::getBizseq,tswritscontent.getBizseq())
                .eq(Tswritscontent::getWritsType,tswritscontent.getWritsType())
                .eq(Tswritscontent::getIsTemplate,"0")
                .orderByAsc(Tswritscontent::getParagraphNo);// 是否为模板 “0”否“1”是
        List<Tswritscontent> list = tswritscontentService.list(wrapper);
        if(CollectionUtils.isEmpty(list)){// 没有则查找初始模板
            // 不同文书类型对模板内容有 不同处理
            List<Tswritscontent> contents = getContentsWithWritstype(tswritscontent.getWritsType());
            if (WorkNoUtil.WORKNOTYPE_32.equals(tswritscontent.getWritsType())){//批吊听证告知书
                for (Tswritscontent content : contents) {
                    LambdaQueryWrapper<TsCase> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(TsCase::getBizseq, tswritscontent.getBizseq());
                    TsCase aCase = caseService.getOne(queryWrapper);
                    if (content.getParagraphNo().equals("1")) {
                        String illegalact = illegalactService.getOne(new LambdaQueryWrapper<Illegalact>().eq(Illegalact::getCaseId, aCase.getCaseId())).getIllegact();
                        content.setParagraphContent(content.getParagraphContent().replace("{{违法行为}}",illegalact));
                    }else if(content.getParagraphNo().equals("2")){

                        content.setParagraphContent(content.getParagraphContent().replace("{{查明结果}}",aCase.getSituation()));
                    }
                }
            }else if (WorkNoUtil.WORKNOTYPE_33.equals(tswritscontent.getWritsType())){

            }else if (WorkNoUtil.WORKNOTYPE_31.equals(tswritscontent.getWritsType())){//批吊调查报告
                LocalDateTime now = LocalDateTime.now();
                String year = String.valueOf(now.getYear());
                String month = String.valueOf(now.getMonthValue());
                String day = String.valueOf(now.getDayOfMonth());
                List<Tsbizrevlist> tsbizrevlists = tsbizrevlistService.list(new LambdaQueryWrapper<Tsbizrevlist>().eq(Tsbizrevlist::getBizseq, tswritscontent.getBizseq()).eq(Tsbizrevlist::getIsRemove,"0"));
                for (Tswritscontent content : contents) {
                    if (content.getParagraphNo().equals("1")) {
                        String paragraphContent = content.getParagraphContent();
                        paragraphContent = paragraphContent.replace("{{年}}",year);
                        paragraphContent = paragraphContent.replace("{{月}}",month);
                        paragraphContent = paragraphContent.replace("{{日}}",day);
                        paragraphContent = paragraphContent.replace("{{主体名称}}",tsbizrevlists.get(0).getEntname() + "...等公司");
                        content.setParagraphContent(paragraphContent);

                    }else if(content.getParagraphNo().equals("2")){
                        String paragraphContent = content.getParagraphContent();
                        paragraphContent = paragraphContent.replace("{{年}}",year);
                        paragraphContent = paragraphContent.replace("{{月}}",month);
                        paragraphContent = paragraphContent.replace("{{年度1}}",now.getYear() - 2 + "" );
                        paragraphContent = paragraphContent.replace("{{年度2}}",now.getYear() - 1 + "");
                        content.setParagraphContent(paragraphContent);
                    }
                }
            }
            return RestResult.ok(contents);
        }
        return RestResult.ok(list);
    }*/

    /**
     *  根据业务号及文书类型获取业务对应文书内容
     *
     * @param tswritscontent 文书模板内容参数对象
     * @return
     */
    @ApiOperation("根据业务号及文书类型获取业务对应文书内容")
    @PostMapping("getContentsWithBizseq")
    public RestResult<?> getContentsWithBizseq(@RequestBody Tswritscontent tswritscontent){
        AssertUtils.isNotBlank(tswritscontent.getBizseq(),tswritscontent.getWritsType());
        // 先查找业务中有没有编辑保存过的文书内容，有则返回
        LambdaQueryWrapper<Tswritscontent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Tswritscontent::getBizseq,tswritscontent.getBizseq())
                .eq(Tswritscontent::getWritsType,tswritscontent.getWritsType())
                .eq(Tswritscontent::getIsTemplate,"0")
                .orderByAsc(Tswritscontent::getParagraphNo);// 是否为模板 “0”否“1”是
        List<Tswritscontent> list = tswritscontentService.list(wrapper);
        return RestResult.ok(list);
    }

    /**
     *  根据文书类型获取文书模板内容
     *
     * @param writsType 文书模板内容参数对象
     * @return
     */
    @ApiOperation("根据文书类型获取文书模板内容")
    @PostMapping("getContentsWithWritstype")
    public List<Tswritscontent> getContentsWithWritstype(String writsType){
        AssertUtils.isNotBlank(writsType);
        LambdaQueryWrapper<Tswritscontent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Tswritscontent::getWritsType,writsType)
                .eq(Tswritscontent::getIsTemplate,"1")// 是否为模板
                .orderByAsc(Tswritscontent::getParagraphNo);
        List<Tswritscontent> list = tswritscontentService.list(wrapper);
        return list;
    }

    /**
     * 业务中调整文书内容
     * @param contentsList 文书模板内容参数对象集合
     * @return
     */
    @ApiOperation("业务中调整文书内容")
    @PostMapping("modifyContentWithBizseq")
    public RestResult<?> modifyContentWithBizseq(@RequestBody List<Tswritscontent> contentsList, HttpServletRequest request){
        if (CollectionUtils.isEmpty(contentsList)){
            return RestResult.error(ResultCode.PARAM_IS_BLANK);
        }
        AICUser user = getLoginUser(request);
        LocalDateTime now = LocalDateTime.now();
        boolean flag = false;
        for (Tswritscontent tswritscontent : contentsList) {
            Tswritscontent tswritscontentModel = new Tswritscontent();
            tswritscontentModel.setBizseq(tswritscontent.getBizseq());
            tswritscontentModel.setParagraphContent(tswritscontent.getParagraphContent());
            tswritscontentModel.setParagraphNo(tswritscontent.getParagraphNo());
            tswritscontentModel.setWritsType(tswritscontent.getWritsType());
            if("1".equals(tswritscontent.getIsTemplate())){
                tswritscontentModel.setIsTemplate("0");
                tswritscontentModel.setCreateUserId(user.getPrimaryKey());
                tswritscontentModel.setCreateTime(now);
                flag = tswritscontentService.save(tswritscontentModel);
            }else {
                tswritscontentModel.setContentId(tswritscontent.getContentId());
                tswritscontentModel.setUpdateTime(now);
                tswritscontentModel.setUpdateUserId(user.getPrimaryKey());
                flag = tswritscontentService.updateById(tswritscontentModel);
            }
        }
        return RestResult.ok(flag);
    }

    /**
     * 业务中保存或更新文书内容
     * @param contentsList
     * @param request
     * @return
     */
    @PostMapping("saveOrUpdateContent")
    public RestResult<?> saveOrUpdateContent(@RequestBody List<Tswritscontent> contentsList, HttpServletRequest request){
        if (CollectionUtils.isEmpty(contentsList)){
            return RestResult.error(ResultCode.PARAM_IS_BLANK);
        }
        AICUser user = getLoginUser(request);
        LocalDateTime now = LocalDateTime.now();
        boolean flag = false;
        for (Tswritscontent tswritscontent : contentsList) {
            LambdaQueryWrapper<Tswritscontent> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Tswritscontent::getBizseq, tswritscontent.getBizseq())
                    .eq(Tswritscontent::getWritsType,tswritscontent.getWritsType())
                    .eq(Tswritscontent::getParagraphNo,tswritscontent.getParagraphNo());
            Tswritscontent tswritscontentDB = tswritscontentService.getOne(wrapper);
            if(tswritscontentDB != null){
                tswritscontentDB.setParagraphContent(tswritscontent.getParagraphContent());
                tswritscontentDB.setUpdateUserId(user.getPrimaryKey());
                tswritscontentDB.setUpdateTime(now);
                flag = tswritscontentService.updateById(tswritscontentDB);
            }else {
                tswritscontent.setCreateUserId(user.getPrimaryKey());
                tswritscontent.setCreateTime(now);
                tswritscontent.setIsTemplate("0");
                flag = tswritscontentService.save(tswritscontent);
            }
        }

        return RestResult.ok(flag);
    }
}

