package com.sifang.modules.sunshine.SystemSetting.controller;

import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.utils.EmployeRoleUtils;
import com.sifang.modules.esign.cn.tsign.hz.exception.EsignDemoException;
import com.sifang.modules.flowpath.service.TraderAgentService;
import com.sifang.modules.flowpath.service.TraderApplyService;
import com.sifang.modules.platform.service.AddressService;
import com.sifang.modules.platform.utils.AddressUtils;
import com.sifang.modules.q7link.utils.Q7DataUtil;
import com.sifang.modules.setting.dao.MemberDao;
import com.sifang.modules.setting.service.MemberService;
import com.sifang.modules.sunshine.SystemSetting.dao.ProjectSettingDao;
import com.sifang.modules.sunshine.SystemSetting.dao.TraderPartnerDao;
import com.sifang.modules.sunshine.SystemSetting.dao.TraderWarehouseRelDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
import com.sifang.modules.sunshine.SystemSetting.form.AddProjectPowerVo;
import com.sifang.modules.sunshine.SystemSetting.form.AddSecondTraderVo;
import com.sifang.modules.sunshine.SystemSetting.form.AddTrader;
import com.sifang.modules.sunshine.SystemSetting.service.DepartmentSettingService;
import com.sifang.modules.sunshine.SystemSetting.service.TraderPcdService;
import com.sifang.modules.sunshine.SystemSetting.service.TraderProjectService;
import com.sifang.modules.sunshine.SystemSetting.service.TraderService;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.partnerManagement.service.PartnerService;
import com.sifang.modules.supply.setting.constant.WarehouseConstants;
import com.sifang.modules.supply.setting.dao.CrmSupplyWarehouseDao;
import com.sifang.modules.supply.stock.utils.MaterialUtils;
import com.sifang.modules.supply.warehouse.dao.InventoryOrderDao;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.dao.UserDao;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.GuardUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.web.BaseExceptionController;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author hongzq
 * 代理商管理
 */
@Controller
@RequestMapping(value = "${adminPath}/trader")
public class TraderController extends BaseExceptionController {

    Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    TraderService traderService;

    @Autowired
    MemberService memberService;

    @Autowired
    MemberDao memberDao;
    @Autowired
    AddressService addressService;

    @Autowired
    private TraderApplyService traderApplyService;

    @Autowired
    private TraderProjectService traderProjectService;

    @Autowired
    private TraderAgentService agentService;

    @Autowired
    private DepartmentSettingService departmentService;

    @Autowired
    private CrmSupplyWarehouseDao supplyWarehouseDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private TraderWarehouseRelDao traderWarehouseRelDao;

    @Autowired
    private TraderPcdService pcdService;

    @Autowired
    ProjectSettingDao projectSettingDao;

    @Autowired
    InventoryOrderDao inventoryOrderDao;


    @Autowired
    CrmSupplyWarehouseDao crmSupplyWarehouseDao;

    @Autowired
    PartnerService partnerService;

    @Autowired
    TraderPartnerDao traderPartnerDao;


    @RequestMapping(value = "index")
    public String traderList(Model model) {

        User user = UserUtils.getUser();
        model.addAttribute("user", user);
        return "modules/yangguang/systemSetting/trader/traderList";
    }


    @RequestMapping(value = "toImport")
    public String toImport(){
        return "modules/yangguang/systemSetting/trader/importTrader";
    }


    @RequestMapping(value = "toEmpower")
    public String toEmpower(String id, Model model) {
        model.addAttribute("id", id);
        model.addAttribute("trader", traderService.getById(id));
        // 获取代理商项目
        model.addAttribute("projectList", traderProjectService.getTraderProject(id));
        // 获取代理商区域设置
        model.addAttribute("areaList", pcdService.getListByTraderId(id));
        //获取代理商授权资方
        model.addAttribute("partnerList",traderPartnerDao.getListByTraderId(id));
        //获取所有一级部门
        //List<Record> list = departmentService.getTopDeptByTwo();
        //model.addAttribute("depList",list);

        return "modules/yangguang/systemSetting/trader/addProjectEmpower";
    }

    @RequestMapping(value="toInint")
    public String toInint(String id, Model model) {
        model.addAttribute("id", id);
        model.addAttribute("trader", traderService.getById(id));

        // 获取代理商项目
        model.addAttribute("projectList", traderProjectService.getTraderProject(id));
        // 获取代理商区域设置
        //model.addAttribute("areaList", inventoryOrderDao.inintStock(id));
        model.addAttribute("areaList", crmSupplyWarehouseDao.findByTypeAndAscriptionId("2",id));
        return "modules/yangguang/systemSetting/trader/addInintStock";
    }

    @RequestMapping(value = "toTwoEmpower")
    public String toTwoEmpower(String id, Model model) {
        model.addAttribute("id", id);
        model.addAttribute("trader", traderService.getById(id));
        // 获取代理商项目
        //model.addAttribute("projectList", traderProjectService.getTraderProject(id));
        // 获取代理商区域设置
        model.addAttribute("areaList", pcdService.getListByTraderId(id));
        //获取所有一级部门
        //List<Record> list = departmentService.getTopDeptByTwo();
        //model.addAttribute("depList",list);

        return "modules/yangguang/systemSetting/trader/addProjectEmpowerTwo";
    }

    @RequestMapping(value = "toAddProjectPage")
    public String toAddProjectPage(String traderId,Model model) {
        //获取代理商
        model.addAttribute("projectList", memberService.getProjectListsByTraderId(traderId));
        model.addAttribute("paterns", partnerService.partnerList());
        model.addAttribute("traderId", traderId);
        return "modules/yangguang/systemSetting/trader/addProject";
    }
    @ResponseBody
    @RequestMapping(value = "getProjectListByPartnerId")
    public Object getProjectListByPartnerId(HttpServletRequest request) {
        String partnerId = request.getParameter("partnerId");
        String traderId = request.getParameter("traderId");
        List<Record> list = memberService.getProjectListsByTraderId(traderId);
        List<Record> list2;
        if (StringUtil.isBlank(partnerId)){
            list2 = list;
        }else {
            list2 = list.stream().filter(r -> partnerId.equals(r.getStr("management"))).collect(Collectors.toList());
        }
        return list2;
    }

    @RequestMapping(value = "toAddPartnerPage")
    public String toAddPartnerPage(Model model) {
        //获取资方
        model.addAttribute("partnerList", partnerService.partnerList());
        return "modules/yangguang/systemSetting/trader/addPartner";
    }

    @RequestMapping(value = "toAddAreaPage")
    public String toAddAreaPage(Model model) {
        //获取所有的省
        model.addAttribute("province", addressService.getProvinces());
        return "modules/yangguang/systemSetting/trader/addArea";
    }

    /**
     * 邀請簽約
    */
    @RequestMapping(value = "inviteSign")
    public String inviteSign(String id,Model model){
        model.addAttribute("id",id);
        //获取所有项目信息
        CrmTrader trader = traderService.getById(id);
        List<Record> agent = traderApplyService.findAgentListByTraderId(id);
        model.addAttribute("agents", agent);
        model.addAttribute("trader", trader);
        return "modules/yangguang/systemSetting/trader/traderSignDetail";
    }


    @ResponseBody
    @RequestMapping(value = "addProjectEmpower")
    public Result<Void> addProjectEmpower(@RequestBody AddProjectPowerVo powerVo){
        GuardUtils.notBlank(powerVo.getTraderId(), "代理商为空");
        traderProjectService.saveTraderProject(powerVo);
        return Result.ok();
    }



    @ResponseBody
    @RequestMapping(value = "checkImportTrader")
    public Object checkImportTrader(MultipartFile file) throws IOException {
        Map<String, String> params = Maps.newHashMap();
        params.put("extName", StringUtil.getFileExtName(file.getOriginalFilename()));
        Map<String, Object> retMap = traderService.checkImportTrader(params, file.getInputStream());
        return JSONObject.fromObject(retMap);
    }

    @RequestMapping(value = "importTrader")
    @ResponseBody
    public JSONObject importTrader(MultipartFile file) throws IOException {
        Map<String, String> params = Maps.newHashMap();
        params.put("fileName", file.getOriginalFilename());
        Map<String, Object> retMap = traderService.importGoods(params, file.getInputStream());
        return JSONObject.fromObject(retMap);
    }

    /**
     * 修改代理商
    */
    @RequestMapping(value = "editApply")
    public String editApply(String id, Model model) {
        List<Record> province = addressService.getProvinces();//获取所有的省

        if (org.apache.commons.lang3.StringUtils.isNotBlank(id)) {
            CrmTrader trader = traderService.getById(id);
            List<Record> agent = traderApplyService.findAgentListByTraderId(id);
            model.addAttribute("agents", agent);
            model.addAttribute("trader", trader);

            List<Record> city = AddressUtils.getCityByProName(trader.getProvince());
            List<Record> area = AddressUtils.getAreaByCityName(trader.getCity());
            model.addAttribute("city", city);
            model.addAttribute("area", area);

            List<Record> city2 = AddressUtils.getCityByProName(trader.getTakeDeliveryProvince());
            List<Record> area2 = AddressUtils.getAreaByCityName(trader.getTakeDeliveryCity());
            model.addAttribute("city2", city2);
            model.addAttribute("area2", area2);
        }
        model.addAttribute("province", province);
        List<Record> qqProjectCodes= Q7DataUtil.getAllQQProjectCode();
        model.addAttribute("qqProjectCodes",qqProjectCodes);
        return "modules/yangguang/systemSetting/trader/editApply";
    }




    /**
     * 查看代理商详情
    */
    @RequestMapping(value = "traderDetail")
    public String traderDetail(String id, Model model,HttpServletRequest request){
        List<Record> province = addressService.getProvinces();//获取所有的省

        if (org.apache.commons.lang3.StringUtils.isNotBlank(id)) {
            CrmTrader trader = traderService.getById(id);
            model.addAttribute("trader", trader);
            List<Record> agent = traderApplyService.findAgentListByTraderId(id);
            model.addAttribute("agents", agent);

        }
        model.addAttribute("province", province);
        return "modules/yangguang/systemSetting/trader/traderDetail";


    }


    @ResponseBody
    @RequestMapping(value = "add")
    public Result<Void> addOrEditTrader(@Valid AddTrader req, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return errRet(bindingResult);
        }
        traderService.addOrEditTrader(req);
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping(value = "delete")
    public Result<Void> deleteTrader(String ids){
        GuardUtils.notBlank(ids, "ids不能为空");
        traderService.deleteTrader(ids);
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping(value = "list")
    public Object getSite(HttpServletRequest request){
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> map= getParams(request);
        User user = UserUtils.getUser();
        if(User.USER_TYPE_WXG.equals(user.getUserType())){  //平台员工
            EmployeRoleUtils.getUserDataAuthority(user.getId(),map);
        }
        //让分页查询语句，将所有数据都查询出来
        map.put("ifNotCheckStatus","not");
        traderService.listTrader(page, map);
        return page.renderJson();
    }

    /**
     * 根据省获取所有代理商
     */
    @ResponseBody
    @RequestMapping(value = "findTraderListByProvince")
    public Object findTraderListByProvince(HttpServletRequest request) {
        String province = request.getParameter("province");
        List<Record> list = traderService.findTraderListByProvince(province);
        return  list;
    }


    /**
     * 根据授权地区省获取所有代理商
     */
    @ResponseBody
    @RequestMapping(value = "findTraderListByProvinces")
    public Object findTraderListByProvinces(HttpServletRequest request) {
        String province = request.getParameter("province");
        List<Record> list = traderService.findTraderListByProvinces(province);
        return  list;
    }



    /**
     * 根据省获取所有项目
     */
    @ResponseBody
    @RequestMapping(value = "findProjectListByProvince")
    public Object findProjectListByProvince(HttpServletRequest request) {
        String province = request.getParameter("province");
        List<Record> list = projectSettingDao.getProjectInfoByArea(province);
        return  list;
    }

    /**
     * 邀请签约
    */
    @ResponseBody
    @RequestMapping(value = "inviteSignQr")
    public Object inviteSignQr(HttpServletRequest request){
        String id = request.getParameter("id");
        Result result = new Result();
        String traderId = request.getParameter("traderId");
        try {
          String  url = agentService.inviteSign(id);
            result.setData(url);
            result.setCode("200");
            return result;
        } catch (EsignDemoException e) {
            e.printStackTrace();
            logger.error(">>>>>>>>>>>>>>>>>>inviteSignQr  e:{}",e);
            return Result.fail(e.getMessage());
        }catch (Exception m){
            m.printStackTrace();
            logger.error(">>>>>>>>>>>>>>>>>>inviteSignQr  m:{}",m);
            return Result.fail(m.getMessage());
        }
    }

    @RequestMapping(value = "second/index")
    public String secondTraderList() {
        return "modules/yangguang/systemSetting/trader/secondTraderList";
    }

    @RequestMapping(value = "second/add")
    public String addSecondTrader(String id, Model model) {
        if (StringUtil.isNotBlank(id)) {
            CrmTrader trader = traderService.getById(id);
            model.addAttribute("trader", trader);
            User user = userDao.get(trader.getUserId());
            model.addAttribute("user", user);
            List<String> warehouseIdList = traderWarehouseRelDao.findByTraderId(id);
            StringBuilder warehouseIds = new StringBuilder();
            if (warehouseIdList.size() > 0) {
                for (String str : warehouseIdList) {
                    warehouseIds.append(",").append(str);
                }
                warehouseIds = new StringBuilder(warehouseIds.substring(1));
            }
            model.addAttribute("warehouseIds", warehouseIds.toString());
        }
        model.addAttribute("id", id);
        User user = UserUtils.getUser();
        //获取所有仓库信息
        String traderId;
        if (User.USER_TYPE_ADVISOR.equals(user.getUserType())) {
            traderId = CrmUtils.getTraderId(user.getId());
        } else {
            traderId = CrmUtils.getTraderIdByUserId(user.getId());
        }
        List<Record> warehouseList = supplyWarehouseDao.findByTypeAndAscriptionId(WarehouseConstants.WAREHOUSE_TYPE_JXS, traderId);
        model.addAttribute("warehouses", warehouseList);
        model.addAttribute("firstTraderName", CrmUtils.getTraderNameById(traderId));
        return "modules/yangguang/systemSetting/trader/addSecondTrader";
    }

    @ResponseBody
    @RequestMapping(value = "second/save")
    public Result save(@Valid @RequestBody AddSecondTraderVo secondTraderVo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return errRet(bindingResult);
        }
        try {
            //去掉登录账号的前后空格
            secondTraderVo.setLoginName( secondTraderVo.getLoginName().trim() );
            if (StringUtil.isBlank(secondTraderVo.getId())) {
                return traderService.saveSecondTrader(secondTraderVo);
            } else {
                return traderService.editSecondTrader(secondTraderVo);
            }
        } catch (Exception e) {
            logger.error("新增二级代理商错误：{}", e.getMessage());
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping(value = "second/changeStatus")
    public Result changeStatusSecondTrader(String id, String status) {
        try {
            return traderService.changeStatusSecondTrader(id, status);
        } catch (Exception e) {
            logger.error("二级代理商 启用/禁用 错误：{}", e.getMessage());
            return Result.fail(e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping(value = "first/changeStatus")
    public Result changeStatusFirstTrader(String id, String status) {
        try {
            return traderService.changeStatusFirstTrader(id, status);
        } catch (Exception e) {
            logger.error("代理商 启用/禁用 错误：{}", e.getMessage());
            return Result.fail(e.getMessage());
        }
    }
    /**
     * 查看二级代理商详情
     */
    @RequestMapping(value = "second/detail")
    public String secondTraderDetail(String id, Model model) {
        CrmTrader trader = traderService.getById(id);
        User user = userDao.get(trader.getUserId());
        List<String> warehouseIdList = traderWarehouseRelDao.findByTraderId(id);
        StringBuilder warehouseIds = new StringBuilder();
        if (warehouseIdList.size() > 0) {
            for (String str : warehouseIdList) {
                warehouseIds.append(",").append(str);
            }
            warehouseIds = new StringBuilder(warehouseIds.substring(1));
        }
        model.addAttribute("trader", trader);
        model.addAttribute("user", user);
        model.addAttribute("warehouseIds", warehouseIds.toString());
        //获取所有仓库信息
        List<Record> warehouseList = supplyWarehouseDao.findByTypeAndAscriptionId(WarehouseConstants.WAREHOUSE_TYPE_JXS, trader.getParentId());
        model.addAttribute("warehouses", warehouseList);
        return "modules/yangguang/systemSetting/trader/secondTraderDetail";
    }
}
