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

import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.platform.service.AddressService;
import com.sifang.modules.platform.utils.AddressUtils;
import com.sifang.modules.sunshine.SystemSetting.dao.CrmProjectCompanyPcdDao;
import com.sifang.modules.sunshine.SystemSetting.dao.ProjectCompanyDao;
import com.sifang.modules.sunshine.SystemSetting.entity.ProjectPcd;
import com.sifang.modules.sunshine.SystemSetting.service.ProjectCompanyService;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.SystemSetting.vo.ProjectCompanySettingsVo;
import com.sifang.modules.sunshine.partnerManagement.service.PartnerService;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.web.BaseExceptionController;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 项目公司设置
 */
@Controller
@RequestMapping(value = "${adminPath}/projectCompany")
public class ProjectCompanyController extends BaseExceptionController {

    @Autowired
    private ProjectCompanyService projectCompanyService;

    @Autowired
    AddressService addressService;

    @Autowired
    ProjectCompanyDao projectCompanyDao;

    @Autowired
    CrmProjectCompanyPcdDao companyPcdDao;
    @Autowired
    PartnerService partnerService;

    //列表页面
    @RequestMapping(value = "settings")
    public String settings(Model model){
        model.addAttribute("partnerList", partnerService.getAllForChoose());
        return "modules/yangguang/systemSetting/projectCompany/projectCompanyPage";
    }

    //列表数据
    @ResponseBody
    @RequestMapping(value = "projectCompanyList")
    public Object projectCompanyList(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        LayuiPage page = new LayuiPage(request);
        projectCompanyService.projectCompanyList(page, map);
        return page.renderJson();
    }

    /**
     * 设置项目公司授权区域
     */
    @RequestMapping(value="rightsForm")
    public String rightsForm(HttpServletRequest reques,Model model){
        String id = reques.getParameter("id");
        model.addAttribute("id",id);
        Record projectCompanyDetail = projectCompanyService.getProjectCompanyDetail(id);

        List<Record> cityList = new ArrayList<>();
        List<Record> areaList = new ArrayList<>();
        if (StringUtil.checkParamsValid(projectCompanyDetail)){
            if (StringUtil.isNotBlank(projectCompanyDetail.getStr("authorize_province"))){
                model.addAttribute("oldProvince", projectCompanyDetail.getStr("authorize_province"));
                for (String s :  projectCompanyDetail.getStr("authorize_province").split(",")) {
                    cityList.addAll(AddressUtils.getCityListByProName(s));
                }
            }
            model.addAttribute("citys",cityList);
            if (StringUtil.isNotBlank(projectCompanyDetail.getStr("authorize_city"))){
                model.addAttribute("oldCitys",projectCompanyDetail.getStr("authorize_city"));
                for (String oldCity : projectCompanyDetail.getStr("authorize_city").split(",")) {
                    areaList.addAll(AddressUtils.getAreaByCityName(oldCity));
                }
            }
            if (StringUtil.isNotBlank(projectCompanyDetail.getStr("authorize_area"))){
                model.addAttribute("oldAreas",projectCompanyDetail.getStr("authorize_area"));
            }

            model.addAttribute("areas",areaList);
        }
        List<Record> province = addressService.getProvinces();//获取所有的省
        model.addAttribute("province",province);
        return "modules/yangguang/systemSetting/projectCompany/rightsForm";
    }


    /**
     * 保存项目公司授权地址
     */
    @ResponseBody
    @RequestMapping("editAuthorizeArea")
    public Result editAuthorizeArea(HttpServletRequest request){

        String id = request.getParameter("id");
        String province = request.getParameter("province");
        String city = request.getParameter("city");
        String area = request.getParameter("area");
        int i = projectCompanyDao.editAuthorizeArea(id, province, city, area);
        if ( i == 1){
            return Result.ok();
        }
        return Result.fail("区域授权失败！");
    }

    @ResponseBody
    @RequestMapping(value = "getAreaListByCity")
    public Object getAreaListByCity(HttpServletRequest request) {
        String city = request.getParameter("city");
        List<Record> list = AddressUtils.getAreaListByProName(city);
        return  list;
    }





    //新增项目公司
    @RequestMapping(value = "addProjectCompany")
    public String addProjectCompany(HttpServletRequest request, Model model){
      //项目公司基础信息不支持编辑
      String id = request.getParameter("id");
        if(StringUtils.isNotBlank(id)){
           Record projectCompany=projectCompanyService.getProjectCompanyDetail(id);
           model.addAttribute("company",projectCompany);
            List<Record> city = AddressUtils.getCityByProName(projectCompany.getStr("province"));
            List<Record> area = AddressUtils.getAreaByCityName(projectCompany.getStr("city"));
            model.addAttribute("city", city);
            model.addAttribute("area", area);
            model.addAttribute("authorizeProvince",projectCompany.getStr("authorize_province"));
            model.addAttribute("authorizeCity", AddressUtils.getCityByProName(projectCompany.getStr("authorize_province")));
            model.addAttribute("authorizeArea",AddressUtils.getAreaByCityName(projectCompany.getStr("authorize_city")));
        }
        List<Record> province = addressService.getProvinces();//获取所有的省
        model.addAttribute("province", province);
        List<ProjectPcd> byProjectId = companyPcdDao.findListByProjectId(id);
        model.addAttribute("areaList",byProjectId);
        model.addAttribute("paterns", partnerService.partnerList());
        return "modules/yangguang/systemSetting/projectCompany/addProjectCompanyPage";
    }

    @RequestMapping(value = "projectCompanyDetail")
    public String projectCompanyDetail(HttpServletRequest request, Model model){
        //项目公司基础信息不支持编辑
        String id = request.getParameter("id");
        if(StringUtils.isNotBlank(id)){
            Record projectCompany=projectCompanyService.getProjectCompanyDetail(id);
            model.addAttribute("company",projectCompany);
            List<Record> city = AddressUtils.getCityByProName(projectCompany.getStr("province"));
            List<Record> area = AddressUtils.getAreaByCityName(projectCompany.getStr("city"));
            model.addAttribute("city", city);
            model.addAttribute("area", area);
            model.addAttribute("authorizeProvince",projectCompany.getStr("authorize_province"));
            model.addAttribute("authorizeCity", AddressUtils.getCityByProName(projectCompany.getStr("authorize_province")));
            model.addAttribute("authorizeArea",AddressUtils.getAreaByCityName(projectCompany.getStr("authorize_city")));
        }
        List<Record> province = addressService.getProvinces();//获取所有的省
        model.addAttribute("province", province);
        List<ProjectPcd> byProjectId = companyPcdDao.findListByProjectId(id);
        model.addAttribute("areaList",byProjectId);
        model.addAttribute("paterns", partnerService.partnerList());
        return "modules/yangguang/systemSetting/projectCompany/projectCompanyDetail";
    }


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


    //保存项目公司
    @ResponseBody
    @RequestMapping(value = "saveProjectCompany")
    public Result saveProjectCompany(@RequestBody ProjectCompanySettingsVo settings){
        projectCompanyService.saveProjectCompany(settings);
        return Result.ok();
    }

    // 启用、禁用  项目公司   0.启用 1.禁用 2.删除
    @ResponseBody
    @RequestMapping(value = "changeCompanyStatus")
    public Result changeCompanyStatus(String id,String status){
        projectCompanyService.changeCompanyStatus(id,status);
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping(value = "getProjectCompany")
    public Object getProjectCompany(){
        return projectCompanyService.getProjectCompany();
    }

    /**
     * 导入公司信息
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "importProjectCompany")
    @ResponseBody
    public JSONObject importProjectCompany(MultipartFile file) throws Exception {
        Map<String, String> params = Maps.newHashMap();
        params.put("fileName", file.getOriginalFilename());
        Map<String, Object> retMap = projectCompanyService.importProjectCompany(params, file.getInputStream());
        System.out.println(retMap);
        return JSONObject.fromObject(retMap);
    }

    /**
     * 检验项目公司信息格式
     * @param file
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "checkImportProjectCompany")
    public Object checkImportProjectCompany(MultipartFile file) throws Exception {
        Map<String, String> params = Maps.newHashMap();
        params.put("extName", StringUtil.getFileExtName(file.getOriginalFilename()));
        Map<String, Object> retMap = projectCompanyService.checkImportProjectCompany(params, file.getInputStream());
        return JSONObject.fromObject(retMap);
    }

    /**
     * 导入项目公司弹框
     */
    @RequestMapping(value = "importProjectCompanyForm")
    public String importProjectCompanyForm(){
        return "modules/yangguang/systemSetting/projectCompany/importProjectCompanyForm";
    }

    /**
     * 导入授权区域信息
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "importAuthorizedArea")
    @ResponseBody
    public JSONObject importAuthorizedArea(MultipartFile file) throws Exception {
        Map<String, String> params = Maps.newHashMap();
        params.put("fileName", file.getOriginalFilename());
        Map<String, Object> retMap = projectCompanyService.importAuthorizedArea(params, file.getInputStream());
        System.out.println(retMap);
        return JSONObject.fromObject(retMap);
    }

    /**
     * 检验授权区域格式
     * @param file
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "checkAuthorizedArea")
    public Object checkAuthorizedArea(MultipartFile file) throws Exception {
        Map<String, String> params = Maps.newHashMap();
        params.put("extName", StringUtil.getFileExtName(file.getOriginalFilename()));
        Map<String, Object> retMap = projectCompanyService.checkAuthorizedArea(params, file.getInputStream());
        return JSONObject.fromObject(retMap);
    }

    /**
     * 导入授权区域弹框
     */
    @RequestMapping(value = "importAuthorizedAreaForm")
    public String importAuthorizedAreaForm(){
        return "modules/yangguang/systemSetting/projectCompany/importAuthorizedAreaForm";
    }

    //查看印章跨企业授权的合同
    @ResponseBody
    @RequestMapping(value = "viewSealAuthContract")
    public Result viewSealAuthContract(String companyId){
        String url=projectCompanyService.viewSealAuthContract(companyId);
        return Result.success(url);
    }

    //印章授权
    @ResponseBody
    @RequestMapping(value = "createSealAuth")
    public Result createSealAuth(String companyId){
        String msg=projectCompanyService.createSealAuth(companyId);
        if(StringUtil.isNotBlank(msg)){
            return Result.success(msg);
        }
        return Result.fail("印章授权失败！");
    }
}
