package com.jeeplus.business.workClientInfo.controller;

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.business.finance.util.EasyPoiUtil;
import com.jeeplus.business.monthly.service.dto.MonthlyDTO;
import com.jeeplus.business.workClientInfo.domain.JyWorkClientInfo;
import com.jeeplus.business.workClientInfo.domain.dto.JyWorkClientInfosDto;
import com.jeeplus.business.workClientInfo.service.JyWorkClientService;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.common.excel.ExcelOptions;
import com.jeeplus.common.excel.annotation.ExportMode;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.logging.constant.enums.LogTypeEnum;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.UserDTO;
//import com.jeeplus.sys.utils.TicketQueryUtils;
//import com.jeeplus.sys.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Api(tags ="jyWorkClientInfo")
@RestController
@RequestMapping(value = "/JyWorkClientInfo/workClientInfo")
public class JyWorkClientController {

    @Resource
    private JyWorkClientService jyWorkClientService;

    /**
     * 客户信息列表
     */
    @ApiOperation(value = "客户信息列表")
    @GetMapping(value = "list")
    public ResponseEntity<IPage<JyWorkClientInfo>> list(JyWorkClientInfo workClientInfo, Page<JyWorkClientInfo> page) throws Exception {

        IPage<JyWorkClientInfo> list = jyWorkClientService.list(page, workClientInfo);
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        for (JyWorkClientInfo info: list.getRecords()) {
            if(userDTO.getName().equals(info.getCreateById()) || userDTO.isAdmin()){
                info.setCreateFlag("1");
            }else{
                info.setCreateFlag("0");
            }
        }
        return ResponseEntity.ok (list);
    }

    /**
     * 客户信息新增/修改
     */
    @ApiOperation(value = "客户信息新增/修改")
    @PostMapping(value = "save")
    public ResponseEntity save(@RequestBody JyWorkClientInfosDto workClientInfosDto) {
        if(ObjectUtil.isNotEmpty(workClientInfosDto)){
            if(ObjectUtil.isNotEmpty(workClientInfosDto.getWorkClientInfo())){
                if(StringUtils.isBlank(workClientInfosDto.getWorkClientInfo().getName())){
                    return ResponseEntity.badRequest().body("保存信息失败，没有获取到用户名称");
                }
                if(!jyWorkClientService.haveWorkClient(workClientInfosDto)){
                    return ResponseEntity.badRequest().body("用户已存在，保存失败");
                }
                if (workClientInfosDto.getWorkClientInfo().getHasUscc().equals("1")){
                    if(!jyWorkClientService.haveUscCode(workClientInfosDto)){
                        return ResponseEntity.badRequest().body("统一社会信用代码已存在，保存失败");
                    }
                }
                if(StringUtils.isNotBlank(workClientInfosDto.getWorkClientInfo().getId())){
                    return ResponseEntity.ok(jyWorkClientService.update(workClientInfosDto));
                }else{
                    return ResponseEntity.ok(jyWorkClientService.save(workClientInfosDto));
                }
            }else{
                return ResponseEntity.badRequest().body("保存信息失败，没有获取到数据");
            }
        }
        return ResponseEntity.badRequest().body("保存信息失败，没有获取到数据");
    }

    /**
     * 新建或修改  判断统一社会信用代码是否重复
     */
    @ApiOperation(value = "判断统一社会信用代码是否重复")
    @GetMapping(value = "haveUscCode")
    public boolean haveUscCode(@RequestParam String id,@RequestParam String uscCode) {
        JyWorkClientInfosDto workClientInfosDto = new JyWorkClientInfosDto();
        JyWorkClientInfo workClientInfo = new JyWorkClientInfo();
        workClientInfo.setId(id);
        workClientInfo.setUscCode(uscCode);
        workClientInfosDto.setWorkClientInfo(workClientInfo);
        return jyWorkClientService.haveUscCode(workClientInfosDto);
    }

    /**
     * 新建或修改  判断客户是否重复
     */
    @ApiOperation(value = "判断客户是否重复")
    @GetMapping(value = "haveWorkClient")
    public boolean haveWorkClient(@RequestParam String id,@RequestParam String name) {
        JyWorkClientInfosDto workClientInfosDto = new JyWorkClientInfosDto();
        JyWorkClientInfo workClientInfo = new JyWorkClientInfo();
        workClientInfo.setId(id);
        workClientInfo.setName(name);
        workClientInfosDto.setWorkClientInfo(workClientInfo);
        return jyWorkClientService.haveWorkClient(workClientInfosDto);
    }

    /**
     * 客户信息删除
     */
    @ApiOperation(value = "客户信息删除")
    @GetMapping(value = "remove")
    public Map<String,Object> remove(@RequestParam String id) {
        return jyWorkClientService.removeById(id);
    }

    /**
     * 客户信息查询
     */
    @ApiOperation(value = "客户信息查询")
    @GetMapping(value = "findById")
    public JyWorkClientInfosDto findById(@RequestParam String id) {
        return jyWorkClientService.findById(id);
    }

    /**
     * 客户信息更新
     */
    @ApiOperation(value = "客户信息更新")
    @PostMapping(value = "update")
    public String update(@RequestBody JyWorkClientInfosDto workClientInfosDto) {
        return jyWorkClientService.update(workClientInfosDto);
    }

    /**
     * 根据名称模糊搜索客户信息
     */
    @ApiOperation(value = "根据名称模糊搜索客户信息")
    @GetMapping(value = "findListByName")
    public List<JyWorkClientInfo> findListByName(@RequestParam String name) {
        return jyWorkClientService.findListByName(name);
    }

    /**
     * 根据关键字查询相关企业
     * @param keyword
     * @return
     */
    @ApiOperation(value = "根据关键字查询相关企业")
    @PostMapping("enterpriseSearchByName")
    public String enterpriseSearchByName(@RequestParam String keyword){
        if(StringUtils.isBlank(keyword)){
            return null;
        }
        return  SpringUtil.getBean ( IUserApi.class ).enterpriseSearchByName(keyword);
    }

    /**
     * 根据id查询企业税号
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id查询企业税号")
    @PostMapping("enterpriseTicketInfo")
    public Object enterpriseTicketInfo(String id){
        if(StringUtils.isBlank(id)){
            return null;
        }
        return SpringUtil.getBean ( IUserApi.class ).enterpriseTicketInfoQueryById(id);
    }

    /**
     * 根据名称、统一社会信用代码判断是否存在
     */
    @ApiOperation(value = "根据名称、统一社会信用代码判断是否存在")
    @GetMapping(value = "isExist")
    public Integer isExist(@RequestParam String param) {
        return jyWorkClientService.isExist(param);
    }

    /**
     * 客户信息列表-组件使用
     */
    @ApiOperation(value = "客户信息列表-组件使用")
    @GetMapping(value = "componentList")
    public ResponseEntity<IPage<JyWorkClientInfo>> componentList(JyWorkClientInfo workClientInfo, Page<JyWorkClientInfo> page) throws Exception {
        QueryWrapper<JyWorkClientInfo> workClientInfoQueryWrapper = QueryWrapperGenerator.buildQueryCondition(workClientInfo, JyWorkClientInfo.class);
        IPage<JyWorkClientInfo> list = jyWorkClientService.componentList(page,workClientInfoQueryWrapper);
        return ResponseEntity.ok (list);
    }

    /**
     * 客户信息查询-组件使用
     */
    @ApiOperation(value = "客户信息查询-组件使用")
    @GetMapping(value = "componentById")
    public JyWorkClientInfo componentById(@RequestParam String id) {
        return jyWorkClientService.componentById(id);
    }


    @ApiOperation(value = "根据id查询客户信息")
    @GetMapping(value = "getBillingListByClientId")
    public ResponseEntity<List<JyWorkClientInfo>> getBillingListByClientId(JyWorkClientInfo workClientInfo) throws Exception {
        List<JyWorkClientInfo> clientInfoList=jyWorkClientService.getBillingListByClientId(workClientInfo);
        return ResponseEntity.ok(clientInfoList);
    }

    @ApiLog(value = "导出成员管理数据", type = LogTypeEnum.EXPORT)
    @GetMapping("export")
    @ApiOperation(value = "导出成员管理数据")
    public void exportFile(JyWorkClientInfo workClientInfo, Page <JyWorkClientInfo> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename();
        String sheetName = options.getSheetName();
        List<JyWorkClientInfo> result = new ArrayList<>();
        if ( ExportMode.current.equals ( options.getMode() ) ) {
            result = jyWorkClientService.list (page,workClientInfo).getRecords();
        } else if (ExportMode.selected.equals ( options.getMode() )) {
            result = jyWorkClientService.list (page,workClientInfo).getRecords().stream ( ).filter ( item ->
                    options.getSelectIds ( ).contains ( item.getId ( ) )
            ).collect ( Collectors.toList ( ) );
        } else {
            page.setSize (-1);
            page.setCurrent (0);
            result = jyWorkClientService.list (page,workClientInfo).getRecords();
        }
        EasyPoiUtil.exportExcel ( result, sheetName,  sheetName, JyWorkClientInfo.class, fileName, response );

    }
}
