package com.gci.boot.modules.basedata.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
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.gci.boot.common.log.annotation.AddSysLog;
import com.gci.boot.common.validated.SaveValidated;
import com.gci.boot.common.validated.UpdateValidated;
import com.gci.boot.common.vo.Result;
import com.gci.boot.modules.basedata.entity.TbCustomerArchives;
import com.gci.boot.modules.basedata.service.ITbCustomerArchivesService;
import com.gci.boot.modules.system.entity.SysDepart;
import com.gci.boot.modules.system.service.ISysDepartService;
import com.gci.boot.modules.system.vo.LoginUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Api(tags="客户档案表对象")
@RestController
@RequestMapping("/base/customer")
@Slf4j
public class TbCustomerArchivesController {
    @Autowired
    private ITbCustomerArchivesService tbCustomerArchivesService;
    @Autowired
    private ISysDepartService sysDepartService;

    /**
     * 分页列表查询
     *
     * @param archives
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AddSysLog("客户档案-分页列表查询")
    @ApiOperation(value="客户档案表对象-分页列表查询", notes="客户档案表对象-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(TbCustomerArchives archives,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req ) {
        Page<TbCustomerArchives> page = new Page<TbCustomerArchives>(pageNo, pageSize);
        LambdaQueryWrapper<TbCustomerArchives> queryWrapper = new LambdaQueryWrapper<TbCustomerArchives>()
                .like(StrUtil.isNotBlank(archives.getName()), TbCustomerArchives::getName,archives.getName())
                .like(StrUtil.isNotBlank(archives.getShortened()), TbCustomerArchives::getShortened,archives.getShortened())
                .like(StrUtil.isNotBlank(archives.getContact()), TbCustomerArchives::getContact,archives.getContact())
                .like(StrUtil.isNotBlank(archives.getPhone()), TbCustomerArchives::getPhone,archives.getPhone())
                .eq(StrUtil.isNotBlank(archives.getSysOrgCode()), TbCustomerArchives::getSysOrgCode, archives.getSysOrgCode())
                .eq(archives.getCancelFlag()!=null, TbCustomerArchives::getCancelFlag, archives.getCancelFlag())
                .orderByDesc(TbCustomerArchives::getCreateTime);
        IPage<TbCustomerArchives> pageList = tbCustomerArchivesService.page(page, queryWrapper);

        for(TbCustomerArchives tbCustomerArchives:pageList.getRecords()){
            if(StrUtil.isNotBlank(tbCustomerArchives.getContact())){
                tbCustomerArchives.setContactList(JSONUtil.toList(tbCustomerArchives.getContact(), String.class));
            }
            if(StrUtil.isNotBlank(tbCustomerArchives.getPhone())){
                tbCustomerArchives.setPhoneList(JSONUtil.toList(tbCustomerArchives.getPhone(), String.class));
            }
            if(CollectionUtils.isNotEmpty(tbCustomerArchives.getContactList()) && CollectionUtils.isNotEmpty(tbCustomerArchives.getPhoneList())){
                if(tbCustomerArchives.getContactList().size()!= tbCustomerArchives.getPhoneList().size()){
                    tbCustomerArchives.setNameAndPhone("联系人和电话数量不一致");
                }else{
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < tbCustomerArchives.getContactList().size(); i++) {
                        if (i > 0) {
                            stringBuilder.append(",");
                        }
                        stringBuilder.append(tbCustomerArchives.getContactList().get(i));
                        stringBuilder.append(":");
                        stringBuilder.append(tbCustomerArchives.getPhoneList().get(i));
                    }
                    String nameAndPhone = stringBuilder.toString();

                    tbCustomerArchives.setNameAndPhone(nameAndPhone);
                }
            }
        }
        return Result.ok(pageList);
    }

    @AddSysLog("客户档案-下拉分页列表查询")
    @ApiOperation(value="客户档案表对象-下拉分页列表查询", notes="客户档案表对象-下拉分页列表查询")
    @GetMapping(value = "/selList")
    public Result<?> selectPageList(TbCustomerArchives archives,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req ) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(sysUser!=null) {
            //如果登录账号属于客户公司，限制只能查自己机构的客户
            List<SysDepart> departs = sysDepartService.getDepartByUserId(sysUser.getId());
            if(departs.size()>0){
                for(SysDepart depart:departs){
                    if(depart != null && depart.getOrgCategory() == 3){
                        archives.setSysOrgCode(sysUser.getOrgCode());
                    }else{
                        archives.setSysOrgCode(null);
                        break;
                    }
                }
            }
        }
        return queryPageList(archives, pageNo, pageSize, req);
    }
    /**
     *   添加
     */
    @AddSysLog("客户档案-添加")
    @ApiOperation(value="客户档案表对象-添加", notes="客户档案表对象-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody @Validated(SaveValidated.class) TbCustomerArchives archives) {
        if(tbCustomerArchivesService.checkDuplicateDepart(archives.getSysOrgCode(),archives.getId())){
            return Result.error(101,"客户数据不能重复设置已使用的部门！");
        }
        boolean check = tbCustomerArchivesService.check(archives);
        if (!check) {
            return Result.error(101,"全称、简称信息不能重复！");
        }
        if(CollectionUtils.isNotEmpty(archives.getContactList())){
            archives.setContact(JSONUtil.toJsonPrettyStr(archives.getContactList()));
        }
        if(CollectionUtils.isNotEmpty(archives.getPhoneList())){
            archives.setPhone(JSONUtil.toJsonPrettyStr(archives.getPhoneList()));
        }

        tbCustomerArchivesService.save(archives);
        return Result.ok("添加成功！");
    }

    /**
     *   编辑
     */
    @AddSysLog("客户档案-编辑")
    @ApiOperation(value="客户档案表对象-编辑", notes="客户档案表对象-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody @Validated(UpdateValidated.class)TbCustomerArchives archives) {
        if(tbCustomerArchivesService.checkDuplicateDepart(archives.getSysOrgCode(),archives.getId())){
            return Result.error(101,"客户数据不能重复设置已使用的部门！");
        }
        boolean check = tbCustomerArchivesService.check(archives);
        if (!check) {
            return Result.error(101,"全称、简称信息不能重复！");
        }
        TbCustomerArchives one = tbCustomerArchivesService.getById(archives.getId());
        if(Objects.isNull(one)){
            return Result.error(101,"该数据不存在，请刷新！");
        }
        if(one.getCancelFlag() == 1){
            return Result.error(101,"该数据已作废，不可编辑！");
        }
        if(CollectionUtils.isNotEmpty(archives.getContactList())){
            archives.setContact(JSONUtil.toJsonPrettyStr(archives.getContactList()));
        }
        if(CollectionUtils.isNotEmpty(archives.getPhoneList())){
            archives.setPhone(JSONUtil.toJsonPrettyStr(archives.getPhoneList()));
        }

        tbCustomerArchivesService.updateById(archives);
        return Result.ok("编辑成功！");
    }

    /**
     *   根据id作废（删除）
     */
    @AddSysLog("客户档案-根据id作废")
    @ApiOperation(value="客户档案表对象-根据id作废（删除）", notes="客户档案表对象-根据id作废（删除）")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        TbCustomerArchives one = tbCustomerArchivesService.getById(id);
        if(Objects.isNull(one)){
            return Result.error(101,"该数据不存在，请刷新！");
        }
        if(one.getCancelFlag() == 1){
            return Result.error(101,"该数据已作废，不可再次作废！");
        }
        one.setCancelFlag(1);
        tbCustomerArchivesService.updateById(one);
        return Result.ok("作废成功！");
    }

    /**
     *   根据id恢复作废数据
     */
    @AddSysLog("客户档案-根据id恢复作废数据")
    @ApiOperation(value="客户档案表对象-根据id恢复作废数据", notes="客户档案表对象-根据id恢复作废数据")
    @GetMapping(value = "/unDelete")
    public Result<?> unDelete(@RequestParam(name="id",required=true) String id) {
        TbCustomerArchives one = tbCustomerArchivesService.getById(id);
        if(Objects.isNull(one)){
            return Result.error(101,"该数据不存在，请刷新！");
        }
        if(one.getCancelFlag() == 0){
            return Result.error(101,"该数据状态正常，无需恢复！");
        }
        one.setCancelFlag(0);
        tbCustomerArchivesService.updateById(one);
        return Result.ok("恢复成功！");
    }

    /**
     *   根据id删除（物理删除）
     */
    @AddSysLog("客户档案-根据id删除")
    @ApiOperation(value="客户档案表对象-根据id删除（物理删除）", notes="客户档案表对象-根据id删除（物理删除）")
    @DeleteMapping(value = "/realDelete")
    public Result<?> realDelete(@RequestParam(name="id",required=true) String id) {
        TbCustomerArchives one = tbCustomerArchivesService.getById(id);
        if(Objects.isNull(one)){
            return Result.error(101,"该数据不存在，请刷新！");
        }
        tbCustomerArchivesService.removeById(one);
        return Result.ok("删除成功！");
    }

    /**
     *  simpleWrite在数据量不大的情况下可以使用（5000以内，具体也要看实际情况），数据量大时要 重复多次写入
     * @param response
     * @param archives
     */
    @AddSysLog("客户档案-导出")
    @GetMapping("/simple/export")
    public Result<?> export(HttpServletResponse response,TbCustomerArchives archives){
        try (OutputStream output = response.getOutputStream()){
            String fileName = "客户档案表.xlsx";
            try {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ";" + "filename*=utf-8''" + fileName);
            LambdaQueryWrapper<TbCustomerArchives> queryWrapper = new LambdaQueryWrapper<TbCustomerArchives>()
                    .like(StrUtil.isNotBlank(archives.getName()), TbCustomerArchives::getName,archives.getName())
                    .like(StrUtil.isNotBlank(archives.getShortened()), TbCustomerArchives::getShortened,archives.getShortened())
                    .like(StrUtil.isNotBlank(archives.getContact()), TbCustomerArchives::getContact,archives.getContact())
                    .like(StrUtil.isNotBlank(archives.getPhone()), TbCustomerArchives::getPhone,archives.getPhone())
                    .orderByDesc(TbCustomerArchives::getCreateTime);
            List<TbCustomerArchives> list = tbCustomerArchivesService.list(queryWrapper);
            EasyExcel.write(output, TbCustomerArchives.class).sheet("客户档案表").doWrite(list);
        } catch (IOException e) {
            return Result.error("导出错误！");
        }
        return Result.ok();
    }

    /**
     * 多次读入
     * @param request
     * @return
     */
    @AddSysLog("客户档案-导出")
    @PostMapping("/simple/import")
    public Result<?> simpleImport(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            try(InputStream input = file.getInputStream()) {
                List<TbCustomerArchives> list = EasyExcel.read(input).head(TbCustomerArchives.class).sheet().doReadSync();
                log.info("数据量：{}",list.size());
                tbCustomerArchivesService.saveBatch(list);
            }catch (IOException e){
                return Result.error("导入错误！");
            }
        }
        return Result.ok();
    }

}
