package cn.com.countrygarden.bi.main.controller.insuranceOrder;


import cn.com.countrygarden.bi.main.controller.BaseController;
import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.insuranceOrder.InsuranceOrderAuthorityMapper;
import cn.com.countrygarden.bi.main.dao.insuranceOrder.InsuranceOrderMapper;
import cn.com.countrygarden.bi.main.dto.insuranceOrder.InsuranceOrderDTO;
import cn.com.countrygarden.bi.main.dto.insuranceOrder.InsuranceOrderVO;
import cn.com.countrygarden.bi.main.dto.tbsysuser.RtsUserQuery;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.dup.DupOrgan;
import cn.com.countrygarden.bi.main.model.insuranceOrder.InsuranceOrder;
import cn.com.countrygarden.bi.main.model.insuranceOrder.InsuranceOrderAuthority;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.insuranceOrder.InsuranceOrderService;
import cn.com.countrygarden.bi.main.util.ExportExcelUtil;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 *   保险订单模块接口
 * </p>
 *
 * @author 吕伟峰
 * @date 2020-07-15
 * @version V1.0
 */

@RestController("InsuranceOrderController")
@RequestMapping("/api/insuranceOrder")
public class InsuranceOrderController extends BaseController {
    @Autowired
    private AccessTokenService accessTokenService;
    @Autowired
    private InsuranceOrderService insuranceOrderService;
    @Autowired
    private InsuranceOrderMapper insuranceOrderMapper;
    @Autowired
    private InsuranceOrderAuthorityMapper insuranceOrderAuthorityMapper;

    @GetMapping(value = "/list", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Result list(InsuranceOrderDTO insuranceOrder,
                       @RequestParam(value = "size", required = false, defaultValue = "10") int size,
                       @RequestParam(value = "page", required = false, defaultValue = "1") int page){
        return insuranceOrderService.queryPageList(insuranceOrder,page,size,getAccessToken());
    }


    @GetMapping(value = "/list/user", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Result listUser(RtsUserQuery tbSysUser,
                           @RequestParam(value = "size", required = false, defaultValue = "10") int size,
                           @RequestParam(value = "page", required = false, defaultValue = "1") int page){
        return insuranceOrderService.listUser(tbSysUser,page,size,getAccessToken());
    }

    @GetMapping(value = "/organ/tree", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Result getBaseRtsOrganTree(@RequestParam(value = "userCode", required = false) String userCode){
        return insuranceOrderService.getAllRtsOrganTree(userCode);
    }

    @PostMapping(value = "/editOrganAuth")
    public Result editOrganAuth(
            @RequestParam(value = "userCode",required = true)String userCode,
            @RequestParam(value = "regions",required = true)String regionsCodeStr,
            @RequestParam(value = "projects",required = true)String projectsCodeStr){
        boolean flag = insuranceOrderService.editOrganAuth(userCode, regionsCodeStr,projectsCodeStr, getAccessToken());
        return flag?SUCCESS_MSG:ERROR_MSG;
    }


    @GetMapping(value = "/findRoleregionName", produces = "application/json;charset=utf-8")
    public Result findRoleregionName(HttpServletRequest request) {

        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        List<DupOrgan> result = insuranceOrderService.findDupCommByUserCode(token.getUserCode(),null,true);
        return Response.response(result);
    }

    @GetMapping(value = "/one", produces = "application/json;charset=utf-8")
    public Result queryById(@RequestParam(value = "id", required = true)Integer id,
                            HttpServletRequest request){
        return  insuranceOrderService.queryById(id);
    }

    @PostMapping(value = "/add")
    public Result add(InsuranceOrder insuranceOrder, String projectNameList,
                      HttpServletRequest request){
        return  insuranceOrderService.add(insuranceOrder,getAccessToken(request));
    }

    @PutMapping(value = "/edit")
    public Result edit(InsuranceOrder insuranceOrder, HttpServletRequest request){
        return  insuranceOrderService.edit(insuranceOrder,getAccessToken(request));
    }

    @DeleteMapping(value="/del")
    public Result del(@RequestParam(value = "id", required = true)Integer id){
        return  insuranceOrderService.del(id,getAccessToken());
    }

    @DeleteMapping(value="/delpiliang")
    public Result delpiliang(
            @RequestParam(value="ids",required=false)String ids){
        return  insuranceOrderService.delpiliang(ids,getAccessToken());
    }

    //导出数据
    @RequestMapping(value = "/evaluationrddInsuranceOrder", produces = "multipart/form-data",  method = RequestMethod.GET)
    public void evaluationrddInsuranceOrder(InsuranceOrderDTO insuranceOrder,@RequestParam(value="ids",required=false)String ids, HttpServletRequest request, HttpServletResponse response) throws ParseException, IOException {

        // 获取登录人的角色授权
        //Map<String, Object> rolesMap = insuraService.findRoleInfoMap(getAccessToken().getUserCode());
        List<String> organCodeString=new ArrayList<>();
        List<String> commIdString=new ArrayList<>();
        InsuranceOrderAuthority authority=new InsuranceOrderAuthority();
        authority.setUserCode(getAccessToken().getUserCode());
        authority.setEnable(1);
        List<InsuranceOrderAuthority> orAuthList=insuranceOrderAuthorityMapper.select(authority);
        if(CollectionUtils.isNotEmpty(orAuthList)){
            for (int i = 0; i <orAuthList.size() ; i++) {
                if (orAuthList.get(i).getOrganType().equals(1)){
                    organCodeString.add(orAuthList.get(i).getOrgCode());
                }else if (orAuthList.get(i).getOrganType().equals(0)){
                    commIdString.add(orAuthList.get(i).getCommCode());
                }
            }
        }
/*        List<Integer> paixu=insuraService.roleInfoList(rolesMap);
        for (int i=0;i<paixu.size();i++) {
            if (paixu.get(i)==1){
                break;
            }else if (paixu.get(i)==2){
                break;
            }else if(paixu.get(i)==3){
                organCodeString=managerMapForErpMapper.organCodeString(getAccessToken().getUserCode(),null);
                if(organCodeString==null||organCodeString.size()==0){
                    return;
                }
                break;
            }else if(paixu.get(i)==4){
                commIdString=managerMapForErpMapper.commIdString(getAccessToken().getUserCode());
                if(commIdString==null||commIdString.size()==0){
                    return;
                }
                break;
            }
        }*/

        List<String> rids=new ArrayList<>();
        if(StringUtil.isNotBlank(ids)){
            String[] idString=ids.split(",");
             rids =  Arrays.asList(idString);
        }

        if(StringUtil.isNotBlank(insuranceOrder.getFirstPayDateList())){
            String[] firstPayDate=insuranceOrder.getFirstPayDateList().split(",");
            insuranceOrder.setFirstPayDate1(firstPayDate[0]);
            insuranceOrder.setFirstPayDate2(firstPayDate[1]);
        }

        if(StringUtil.isNotBlank(insuranceOrder.getTransactionDateList())){
            String[] transactionDate=insuranceOrder.getTransactionDateList().split(",");
            insuranceOrder.setTransactionDate1(transactionDate[0]);
            insuranceOrder.setTransactionDate2(transactionDate[1]);
        }

        ExportExcelUtil<InsuranceOrderVO> util = new ExportExcelUtil<InsuranceOrderVO>();
        String[] columnNames = { "区域名称" ,"项目名称" ,"月份" ,"保险单号" ,"产品名称","代理人姓名","业务人员岗位",
                "投保人","被保人","保费","经纪费用收入(不含税)","成交日期","录单时间"};
        Collection<InsuranceOrderVO> list=null;
        if(CollectionUtils.isNotEmpty(organCodeString)&&CollectionUtils.isNotEmpty(commIdString)){
            list=insuranceOrderMapper.evaluationrddInsuranceOrder(insuranceOrder,organCodeString,commIdString,rids);

        }else if(CollectionUtils.isNotEmpty(organCodeString)){
            list=insuranceOrderMapper.evaluationrddInsuranceOrderCodeString(insuranceOrder,organCodeString,rids);
        }else if(CollectionUtils.isNotEmpty(commIdString)){
            list=insuranceOrderMapper.evaluationrddInsuranceOrderComm(insuranceOrder,commIdString,rids);
        }
        response.setContentType("multipart/form-data");
        String fileName = URLEncoder.encode("保险订单.xls","UTF-8");
        response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
        util.exportExcel("保险订单", columnNames, list, response.getOutputStream(), ExportExcelUtil.EXCEL_FILE_2003,null);
    }

    // 下载模版
    @RequestMapping(value = "/download", produces = "multipart/form-data", method = RequestMethod.GET)
    public void downloadTemplate(@RequestParam(value = "errorList",required = false)String errorList,HttpServletRequest request,AccessToken accessToken, HttpServletResponse response) throws ParseException, IOException {
         insuranceOrderService.downloadTemplate(errorList,request,getAccessToken(),response);
    }

    @ResponseBody
    @RequestMapping(value = "/importXlsx", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Result importXlsx(@RequestParam(value = "usname", defaultValue = "", required = false) String usname,HttpServletResponse response,HttpServletRequest request,
                             @RequestParam(value = "file", defaultValue = "", required = true) MultipartFile multipartFile)
            throws ServiceException,IOException{


        if (multipartFile == null) {
            throw new ServiceException("请选择需要上传的文件");
        }
        CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
        if (commonsMultipartFile.isEmpty()) {
            return Response.responseFail("上传文件为空文件");
        }
        String fileName = commonsMultipartFile.getOriginalFilename();
        if (fileName.indexOf(".xlsx") != -1) {
            return insuranceOrderService.excelToxls(request,response,multipartFile, fileName,usname,
                    getAccessToken().getUserCode(), getAccessToken(request));
        }
        return Response.responseFail("模板有误，请下载对应的模版");

    }


    @PostMapping(value = "/erpjiashuju")
    public Result erpjiashuju(){
        insuranceOrderService.erpjiashuju();
        return Response.response("");
    }



}