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

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.financial.Reason;
import cn.com.countrygarden.bi.main.model.twerp.ErpNcData;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysUser;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.UserRoleService;
import cn.com.countrygarden.bi.main.service.excontract.ExContractService;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbHsprCommunityService;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysUserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @program: DPshow_depart
 * @description: 委外合同管理controller
 * @author: SignV
 * @create: 2018-09-05 13:15
 **/
@Controller("ExContractController")
@RequestMapping("/ExContractController")
public class ExContractController {
    @Autowired
    private ExContractService exContractService;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private TbHsprCommunityService tbHsprCommunityService;

    @Autowired
    private TbSysUserService tbSysUserService;


    /*----------------------------------------用户角色信息接口  start-----------------------------------------------*/

    @ResponseBody
    @RequestMapping(value = "/getOrganInfo", method = {RequestMethod.POST, RequestMethod.GET})
    public Result getOrganInfo(String AccessToken) {
        JSONObject returnJson = new JSONObject();
        List<JSONObject> organList = new ArrayList<>();
        //erpNcDataList 去重用
        List<String> organCodeList = new ArrayList<>();

        AccessToken accessToken = accessTokenService.findByToken(AccessToken);
        if (accessToken == null) {
            return Response.responseFail("该账户已在其他地方登录，请重新登录！");
        }
        if (accessToken.getUserCode() == null) {
            return Response.responseFail("该账户已在其他地方登录，请重新登录！");
        }
        String userCode = accessToken.getUserCode();
        //判断用户角色类型
        int userType = userRoleService.judgeRoleExContract(userCode);
        if (userType == 3) {
            return Response.responseFail("该账号没有权限！");
        }
        returnJson.put("userType", userType);
        returnJson.put("userCode", userCode);
        //当用户为区域角色时 获取对应的organList
        List<ErpNcData> erpNcDataList;
        erpNcDataList = tbHsprCommunityService.selectRegionByUserCode(userCode);

        erpNcDataList.forEach(s -> {
            //organCode 去重
            if (organCodeList.contains(s.getOrganCode())) return;
            //放入organName organCode
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("organCode", s.getOrganCode());
            jsonObject.put("organName", s.getOrganName());
            organList.add(jsonObject);
            organCodeList.add(s.getOrganCode());
        });
        returnJson.put("organList", organList);
        return Response.response(returnJson);
    }

    /*----------------------------------------用户角色信息接口  end-----------------------------------------------*/


    /*----------------------------------------供应商月度考核接口  start-----------------------------------------------*/

    @ResponseBody
    @RequestMapping(value = "/getRecordList", method = {RequestMethod.POST, RequestMethod.GET})
    public Result getRecordList(Integer page, Integer pageSize, String data) {
        List<String> organCodeList = JSON.parseObject(data, new TypeReference<List<String>>() {
        });
        if (organCodeList == null)
            return Response.responseFail("请传递正确的区域编码列表！");

        if (page == null) return Response.responseFail("请传递正确的页数！");
        if (pageSize == null) pageSize = 10;
        return Response.response(exContractService.getRecordList(page, pageSize, organCodeList));
    }

    @ResponseBody
    @RequestMapping(value = "/getRecordListByCondition", method = {RequestMethod.POST, RequestMethod.GET})
    public Result getRecordListByCondition(String data, String commname, String supplierName,
                                           String year, String month, String exCode, Integer page, Integer pageSize) {
        List<String> organCodeList = JSON.parseObject(data, new TypeReference<List<String>>() {
        });
        if (organCodeList == null)
            return Response.responseFail("请传递正确的区域编码列表！");

        if (exCode == null || exCode.equals(""))
            return Response.responseFail("请传递正确的委外类别Code！");
        //限制委外类别为1,2,3,0
        if(!(exCode.equals("1") || exCode.equals("2") || exCode.equals("3")) )
            return Response.responseFail("请传递正确的委外类别Code！");

        if (year == null || month == null || year.equals("") || month.equals(""))
            return Response.responseFail("请传递正确的年份或月份！");

        if (page == null) return Response.responseFail("请传递正确的页数！");
        if (pageSize == null) pageSize = 10;

        return Response.response(exContractService.getRecordListByCondition(organCodeList, commname, supplierName, year, month, exCode, page, pageSize,true));
    }

    @ResponseBody
    @RequestMapping(value = "/deleteRecord", method = {RequestMethod.POST, RequestMethod.GET})
    public Result deleteRecord(Integer recordId, String exCode, String userCode) {
        if (recordId == null) return Response.responseFail("请传递正确的考核记录ID！");
        if (exCode == null || exCode.equals("")) return Response.responseFail("请传递正确的委外类别Code！");
        //限制委外类别为1,2,3
        if(!(exCode.equals("1") || exCode.equals("2") || exCode.equals("3")) )
            return Response.responseFail("请传递正确的委外类别Code！");
        if (userCode == null || userCode.equals("")) return Response.responseFail("请传递正确的用户编号！");
        exContractService.deleteRecord(recordId, exCode, userCode);
        return Response.response("数据删除成功！");
    }

    /*----------------------------------------供应商月度考核接口  end-----------------------------------------------*/


    /*----------------------------------------考核详细部分  start-----------------------------------------------*/

    @ResponseBody
    @RequestMapping(value = "/getDataDetail", method = {RequestMethod.POST, RequestMethod.GET})
    public Result getDataDetail(Integer recordId, String exCode) {
        if (recordId == null) return Response.responseFail("请传递正确的考核记录ID！");
        if (exCode == null || exCode.equals("")) return Response.responseFail("请传递正确的委外类别Code！");
        //限制委外类别为1,2,3
        if(!(exCode.equals("1") || exCode.equals("2") || exCode.equals("3")) )
            return Response.responseFail("请传递正确的委外类别Code！");
        return Response.response(exContractService.getDataDetail(recordId, exCode));
    }

    @ResponseBody
    @RequestMapping(value = "/getAuthDetails", method = {RequestMethod.POST, RequestMethod.GET})
    public Result getAuthDetails(Integer codeType, String code) {
        if (codeType == null) return Response.responseFail("请传递正确的编码类型！");
        //限制只能获取这两种类型
        if (codeType != 1 && codeType != 2) return Response.responseFail("请传递正确的编码类型！");
        if (code == null || code.equals("")) return Response.responseFail("请传递正确的区域编码或项目编码！");
        return Response.response(exContractService.getAuthDetails(code, codeType));
    }

    @ResponseBody
    @RequestMapping(value = "/saveOrUpdate", method = {RequestMethod.POST, RequestMethod.GET})
    public Result saveOrUpdate(String data, String exCode, String operaType, String userCode) {
        try {
            exContractService.saveOrUpdateRecord(data, exCode, Integer.parseInt(operaType), userCode);
            return Response.response("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Response.responseFail(e.getMessage());
        }
    }




    /*----------------------------------------考核详细部分  end-----------------------------------------------*/


    /*----------------------------------------Excel导入导出部分  start-----------------------------------------------*/

    @ResponseBody
    @RequestMapping(value = "/exportExContractExcel", method = {RequestMethod.POST, RequestMethod.GET})
    public Result exportExContractExcel(HttpServletResponse response,String data, String commname, String supplierName,
                                        String year, String month, String exCode) {
        List<String> organCodeList = JSON.parseObject(data, new TypeReference<List<String>>() {
        });
        if (organCodeList == null)
            return Response.responseFail("请传递正确的区域编码列表！");

        if (exCode == null || exCode.equals(""))
            return Response.responseFail("请传递正确的委外类别Code！");
        //限制委外类别为1,2,3,0
        if(!(exCode.equals("1") || exCode.equals("2") || exCode.equals("3")) )
            return Response.responseFail("请传递正确的委外类别Code！");

        if (year == null || month == null || year.equals("") || month.equals(""))
            return Response.responseFail("请传递正确的年份或月份！");

        exContractService.exportExContractExcel(response, organCodeList,commname,supplierName,year,month,exCode);
        return Response.response("导出成功！");
    }

    @ResponseBody
    @RequestMapping(value = "/importExContractExcel", method = {RequestMethod.POST})
    public Result importExContractExcel(@RequestParam(value = "exContractUploadFile") MultipartFile multipartFile,String organList,String exCode,String userCode) {
        if (multipartFile == null) {
            return Response.responseFail("请选择需要上传的文件");
        }

        List<JSONObject> organTypeList = JSON.parseObject(organList,new TypeReference<List<JSONObject>>(){});

        if (organTypeList == null){
            return Response.responseFail("请传递正确的区域列表！");
        }

        //保存区域名称以及对于区域编码
        Map<String,String> organMap = new HashMap<>();
        organTypeList.forEach(o ->{
            organMap.put(o.getString("organName"),o.getString("organCode"));
        });

        CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
        if (commonsMultipartFile.isEmpty()) {
            return Response.responseFail("上传文件为空文件");
        }
        String fileName = commonsMultipartFile.getOriginalFilename();
        if (fileName.indexOf(".xlsx") <= 0 || fileName.indexOf(".xls") <= 0) {
            return Response.responseFail("上传的excel文件格式应为：xlsx 或 xls");
        }

        try {
            exContractService.importExContractExcel(multipartFile,organMap,exCode,userCode);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.responseFail(e.getMessage());
        }
        return Response.response("导入成功！");
    }

    @ResponseBody
    @RequestMapping(value = "/downloadExContractExcel", method = {RequestMethod.POST, RequestMethod.GET})
    public Result downloadExContractExcel(HttpServletResponse response,String exCode) {
        if (exCode == null || exCode.equals("")) return Response.responseFail("请传递正确的委外类别Code！");
        //限制委外类别为1,2,3
        if(!(exCode.equals("1") || exCode.equals("2") || exCode.equals("3")) ) return Response.responseFail("请传递正确的委外类别Code！");

        exContractService.downloadExContractExcel(response, exCode);
        return Response.response("下载模板成功！");
    }

    /*----------------------------------------Excel导入导出部分  end-----------------------------------------------*/
}
