package com.jeeplus.finance.workClientInfo.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.common.constant.CacheNames;
import com.jeeplus.common.excel.ExcelOptions;
import com.jeeplus.common.excel.annotation.ExportMode;
import com.jeeplus.common.redis.RedisUtils;
import com.jeeplus.common.utils.ResponseUtil;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.finance.invoice.util.EasyPoiUtil;
import com.jeeplus.finance.workClientInfo.service.CwWorkClientBillingService;
import com.jeeplus.finance.workClientInfo.service.CwWorkClientService;
import com.jeeplus.finance.workClientInfo.service.dto.CwWorkClientBaseDTO;
import com.jeeplus.finance.workClientInfo.service.dto.CwWorkClientBillingDTO;
import com.jeeplus.finance.workClientInfo.service.dto.CwWorkClientContactDTO;
import com.jeeplus.finance.workClientInfo.service.dto.CwWorkClientTempDTO;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.logging.constant.enums.LogTypeEnum;
//import com.jeeplus.sys.utils.DictUtils;
import com.jeeplus.sys.feign.IDictApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.UserDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Api("客户信息")
@RequestMapping(value = "/cw_work_client/info")
public class CwWorkClientController {

    @Resource
    private CwWorkClientService cwWorkClientService;

    @Resource
    private IFlowableApi flowTaskService;

    @Resource
    private CwWorkClientBillingService cwWorkClientBillingService;


    /**
     * 查询客户信息列表
     * @param cwWorkClientBaseDTO
     * @param page
     * @return
     * @throws Exception
     */
    @ApiLog("查询客户信息列表")
    @PreAuthorize("hasAuthority('cw_work_client:info:list')")
    @GetMapping("list")
    public ResponseEntity<IPage<CwWorkClientBaseDTO>> data(CwWorkClientBaseDTO cwWorkClientBaseDTO, Page<CwWorkClientBaseDTO> page) throws Exception {
        IPage<CwWorkClientBaseDTO> result = new Page<CwWorkClientBaseDTO>();
        result = cwWorkClientService.findList (page,cwWorkClientBaseDTO);
//        List<UserDTO> allUserInfo = SpringUtil.getBean(IUserApi.class).getAllUserInfo();
        List<UserDTO> allUserInfo = (List<UserDTO>) RedisUtils.getInstance().get(CacheNames.USER_CACHE_USER_ALL_INFO);
        if (null == allUserInfo || allUserInfo.size() == 0) {
            allUserInfo = SpringUtil.getBean(IUserApi.class).getAllUserInfo();
        }
        result.getRecords().stream().forEach(i -> {
            if (StringUtils.isNotBlank(i.getTaskId()) && StringUtils.isNotBlank(i.getStatus())) {
                if ("2".equals(i.getStatus())) { // “审核中”的数据要获取数据审核人
                    i.setAuditUserIds(flowTaskService.getTaskAuditUsers(i.getTaskId()));  // 获取数据审核人
                }
            }
        });
        List<UserDTO> finalAllUserInfo = allUserInfo;
        result.getRecords().forEach(li -> {
            if (StringUtils.isBlank(li.getCreateBy().getName())){
                //根据项目经理1的id去查项目经理去名称
                UserDTO createBy = li.getCreateBy();
                if (StringUtils.isNotBlank(li.getCreateBy().getId())){
                    UserDTO matchingUser = null;
                    for (UserDTO user : finalAllUserInfo) {
                        if (createBy.getId().equals(user.getId())) {
                            matchingUser = user;
                            break;
                        }
                    }
                    if (matchingUser != null) {
                        String name = matchingUser.getName(); // Assuming the property name is "userName"
                        createBy.setName(name);
                        li.setCreateBy(createBy);
                    }
                }
            }
            if (StringUtils.isBlank(li.getUpdateUserName())) {
                if (StringUtils.isNotBlank(li.getUpdateUser())){
                    UserDTO matchingUser = null;
                    for (UserDTO user : finalAllUserInfo) {
                        if (li.getUpdateUser().equals(user.getId())) {
                            matchingUser = user;
                            break;
                        }
                    }
                    if (matchingUser != null) {
                        String projectMasterName = matchingUser.getName(); // Assuming the property name is "userName"
                        li.setUpdateUserName(projectMasterName);
                    }
                }
            }
        });
        return ResponseEntity.ok (result);
    }

    /**
     * 根据合同id查询对应客户的联系人信息
     * @param cwWorkClientContactDTO
     * @param page
     * @return
     * @throws Exception
     */
    @ApiLog("根据合同id查询对应客户的联系人信息")
    @GetMapping("getContractClientList")
    public ResponseEntity<IPage<CwWorkClientContactDTO>> getContractClientList(CwWorkClientContactDTO cwWorkClientContactDTO, Page<CwWorkClientContactDTO> page) throws Exception {
        IPage<CwWorkClientContactDTO> result = new Page<CwWorkClientContactDTO>();
        result = cwWorkClientService.getContractClientList (page,cwWorkClientContactDTO);
        return ResponseEntity.ok (result);
    }

    /**
     * 查询客户信息列表tree
     * @param cwWorkClientBaseDTO
     * @param page
     * @return
     * @throws Exception
     */
    @ApiLog("查询客户信息列表tree")
    @GetMapping("list_tree")
    public ResponseEntity<IPage<CwWorkClientBaseDTO>> dataTree(CwWorkClientBaseDTO cwWorkClientBaseDTO, Page<CwWorkClientBaseDTO> page) throws Exception {
        IPage<CwWorkClientBaseDTO> result = new Page<CwWorkClientBaseDTO>();
        long l1 = System.currentTimeMillis();
        result = cwWorkClientService.findListTree (page,cwWorkClientBaseDTO);
        long l2 = System.currentTimeMillis();
        System.out.println("查询客户信息列表treeController:" + (l2-l1));
        return ResponseEntity.ok (result);
    }

    /**
     * 查询客户信息数据
     * @param id
     * @return
     */
    @ApiLog("查询客户信息数据")
    // @PreAuthorize ("hasAnyAuthority('cw_work_client:info:view','cw_work_client:info:add','cw_work_client:info:edit')")
    @GetMapping("queryById")
    public ResponseEntity queryById(@RequestParam("id") String id) {
        CwWorkClientBaseDTO cwWorkClientBaseDTO = cwWorkClientService.queryById ( id );
        return ResponseEntity.ok (cwWorkClientBaseDTO);
    }

    /**
     * 保存客户信息
     * @param cwWorkClientBaseDTO
     * @return
     */
    @ApiLog(value = "修改/新增客户信息", type = LogTypeEnum.SAVE)
    @PreAuthorize("hasAnyAuthority('cw_work_client:info:add','cw_work_client:info:edit')")
    @PostMapping("save")
    public ResponseEntity save(@Valid @RequestBody CwWorkClientBaseDTO cwWorkClientBaseDTO) throws Exception {
        cwWorkClientService.saveClient(cwWorkClientBaseDTO);
        return ResponseEntity.ok ("操作成功");
    }

    /**
     * 保存客户信息-流程
     * @param cwWorkClientBaseDTO
     * @return
     */
    @ApiLog(value = "保存客户信息-流程", type = LogTypeEnum.SAVE)
    @PreAuthorize("hasAnyAuthority('cw_work_client:info:add','cw_work_client:info:edit')")
    @PostMapping("saveForm")
    public ResponseEntity saveForm(@Valid @RequestBody CwWorkClientBaseDTO cwWorkClientBaseDTO) throws Exception {
        String id = cwWorkClientService.saveForm(cwWorkClientBaseDTO);
        return ResponseUtil.newInstance().add("businessTable", "cw_work_client_base").add("businessId", id).ok ("操作成功");
    }

    /**
     * 删除业务提问
     * @param ids
     * @return
     */
    @ApiLog(value = "删除客户信息", type = LogTypeEnum.SAVE)
    @PreAuthorize ("hasAuthority('cw_work_client:info:del')")
    @DeleteMapping("delete")
    public ResponseEntity delete(String ids) {
        return cwWorkClientService.deleteByIds(ids);
    }

    /**
     * 根据id修改状态值status
     * @param dto
     * @return
     */
    @ApiOperation(value = "根据id修改状态值status")
    @PostMapping(value = "/updateStatusById")
    public ResponseEntity<String> updateStatusById(@RequestBody CwWorkClientBaseDTO dto) {
        String s = cwWorkClientService.updateStatusById(dto);
        return ResponseEntity.ok(s);
    }


    /**
     * 导出客户数据
     *
     * @param cwWorkClientBaseDTO
     * @param page
     * @param response
     * @throws Exception
     */
    @ApiLog(value = "导出客户数据", type = LogTypeEnum.EXPORT)
    @GetMapping("export")
    @PreAuthorize ("hasAuthority('cw_work_client:info:export')")
    @ApiOperation(value = "导出客户数据")
    public void exportFile(CwWorkClientBaseDTO cwWorkClientBaseDTO, Page <CwWorkClientBaseDTO> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename();
        String sheetName = options.getSheetName();
        List<CwWorkClientBaseDTO> result = new ArrayList<>();
        if ( ExportMode.current.equals ( options.getMode() ) ) {
            result = cwWorkClientService.findList (page,cwWorkClientBaseDTO).getRecords();
        } else if (ExportMode.selected.equals ( options.getMode() )) {
            result = cwWorkClientService.findList (page,cwWorkClientBaseDTO).getRecords().stream ( ).filter ( item ->
                    options.getSelectIds ( ).contains ( item.getId ( ) )
            ).collect ( Collectors.toList ( ) );
        } else {
            page.setSize (-1);
            page.setCurrent (0);
            result = cwWorkClientService.findList (page,cwWorkClientBaseDTO).getRecords();
        }
        result.stream().forEach(item -> {
            if (StringUtils.isNotBlank(item.getType())){
                item.setType(SpringUtil.getBean ( IDictApi.class ).getDictLabel(item.getType(),"cw_work_client_type",""));
            }
            if (StringUtils.isNotBlank(item.getIndustry())){
                item.setIndustry(SpringUtil.getBean ( IDictApi.class ).getDictLabel(item.getIndustry(),"cw_work_client_industry",""));
            }
            if (StringUtils.isNotBlank(item.getIsListed())) {
                item.setIsListed(SpringUtil.getBean ( IDictApi.class ).getDictLabel(item.getIsListed(),"yes_no",""));
            }
            if (StringUtils.isNotBlank(item.getAffiliation())){
                item.setAffiliation(SpringUtil.getBean ( IDictApi.class ).getDictLabel(item.getAffiliation(),"cw_work_client_affiliation",""));
            }
            if (StringUtils.isNotBlank(item.getOwnershipType())){
                item.setOwnershipType(SpringUtil.getBean ( IDictApi.class ).getDictLabel(item.getOwnershipType(),"cw_work_client_ownership_type",""));
            }
            if (StringUtils.isNotBlank(item.getReportType())){
                item.setReportType(SpringUtil.getBean ( IDictApi.class ).getDictLabel(item.getReportType(),"cw_work_client_report_type",""));
            }
            if (StringUtils.isNotBlank(item.getStatus())){
                item.setStatus(SpringUtil.getBean ( IDictApi.class ).getDictLabel(item.getStatus(),"cw_status",""));
            }
        });
        EasyPoiUtil.exportExcel ( result, sheetName,  sheetName, CwWorkClientBaseDTO.class, fileName, response );

    }

    /**
     * 其他人发起修改客户申请
     * @param id
     * @return
     */
    @ApiLog("其他人发起修改客户申请")
    @GetMapping("pushUpdate")
    public ResponseEntity<Map<String,String>> pushUpdate(@RequestParam("id") String id) {
        return cwWorkClientService.pushUpdate ( id );
    }

    /**
     * 终止修改申请
     * @param id
     * @return
     */
    @ApiLog("终止修改申请")
    @GetMapping("stopUpdate")
    public ResponseEntity stopUpdate(@RequestParam("id") String id) throws Exception {
        return cwWorkClientService.stopUpdate ( id );
    }

    /**
     * 驳回/修改/通过申请
     * @param id
     * @return
     */
    @ApiLog("驳回/修改/通过申请")
    @GetMapping("rebackOrAgreeUpdate")
    public ResponseEntity rebackOrAgreeUpdate(@RequestParam("id") String id,@RequestParam("type") String type) {
        return cwWorkClientService.rebackOrAgreeUpdate ( id,type );
    }

    /**
     * 查询社会统一信用代码是否存在
     * @param uscCode
     * @return
     */
    @ApiLog("查询社会统一信用代码是否存在")
    @GetMapping("queryUscCodeIsUse")
    public ResponseEntity<Map<String,String>> queryUscCodeIsUse(@RequestParam("uscCode") String uscCode) {
        ResponseEntity<Map<String, String>> mapResponseEntity = cwWorkClientService.queryUscCodeIsUse(uscCode);
        return mapResponseEntity;
    }

    /**
     * 查询客户名称是否存在
     * @param name
     * @return
     */
    @ApiLog("查询客户名称是否存在")
    @GetMapping("queryNameIsUse")
    public ResponseEntity<Map<String,String>> queryNameIsUse(@RequestParam("name") String name) {
        ResponseEntity<Map<String, String>> mapResponseEntity = cwWorkClientService.queryNameIsUse(name);
        return mapResponseEntity;
    }

    /**
     * 根据客户id查询社会统一信用代码
     * @param id
     * @return
     */
    @ApiLog("根据客户id查询社会统一信用代码")
    @GetMapping("queryUscCodeById")
    public Map<String,Object> queryUscCodeById(@RequestParam("id") String id) {
        Map<String,Object> stringResponseEntity = cwWorkClientService.queryUscCodeById(id);
        return stringResponseEntity;
    }

    /**
     * 根据客户id查询客户名称
     * @param id
     * @return
     */
    @ApiLog("根据客户id查询客户名称")
    @GetMapping("queryNameById")
    public ResponseEntity<String> queryNameById(@RequestParam("id") String id) {
        ResponseEntity<String> stringResponseEntity = cwWorkClientService.queryNameById(id);
        return stringResponseEntity;
    }

    /**
     * 根据客户id查询修改历史
     * @param tempDto
     * @return
     */
    @ApiLog("根据客户id查询修改历史")
    @GetMapping("queryUpdateLogList")
    public ResponseEntity<List<CwWorkClientTempDTO>> queryUpdateLogList(CwWorkClientTempDTO tempDto) {
        return cwWorkClientService.queryUpdateLogList ( tempDto );
    }

    /**
     * 根据客户id查询开票信息
     * @param cwWorkClientBillingDTO
     * @return
     * @throws Exception
     */
    @ApiLog("根据客户id查询开票信息")
    @GetMapping("getBillingListByClientId")
    public ResponseEntity<List<CwWorkClientBillingDTO>> getBillingListByClientId(CwWorkClientBillingDTO cwWorkClientBillingDTO) throws Exception {
        List<CwWorkClientBillingDTO> result = cwWorkClientBillingService.getBillingListByClientId(cwWorkClientBillingDTO);
        return ResponseEntity.ok (result);
    }

}
