package com.ruoyi.web.controller.grid;

import cn.hutool.json.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanCopyUtil;
import com.ruoyi.common.zqt.ZQTPageUtil;
import com.ruoyi.system.domain.grid.*;
import com.ruoyi.system.domain.grid.enums.GridCompanyLevelEnum;
import com.ruoyi.system.domain.grid.ext.GridCompanyExt;
import com.ruoyi.system.domain.grid.ext.GridCompanyPeopleExt;
import com.ruoyi.system.domain.grid.vo.GridCompanySearchParam;
import com.ruoyi.system.domain.other.BsCommon;
import com.ruoyi.system.mapper.grid.GridCompanyMapper;
import com.ruoyi.system.service.grid.GridCompanyPeopleService;
import com.ruoyi.system.service.grid.GridCompanyService;
import com.ruoyi.system.service.grid.GridRegionService;
import com.ruoyi.system.service.other.BsCommonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : peter
 * @date : 2022-05-09 14:33
 */
@Api(tags = "网格管理 - 企业管理")
@RestController
@RequestMapping("/api/grid/company")
public class CompanyController extends BaseController {

    @Autowired
    private GridCompanyService gridCompanyService;
    @Autowired
    private GridCompanyPeopleService gridCompanyPeopleService;
    @Autowired
    private BsCommonService bsCommonService;
    @Autowired
    private GridRegionService gridRegionService;
    @Autowired
    private GridCompanyMapper gridCompanyMapper;

    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public AjaxResult page(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                           @RequestParam(value = "wgCode", required = false) String wgCode,
                           @RequestParam(value = "qylxCode", required = false) String qylxCode,
                           @RequestParam(value = "creditCode", required = false) String creditCode,
                           @RequestParam(value = "value", required = false) String value,
                           @RequestParam(value = "isClosed", required = false) Byte isClosed,
                           @RequestParam(value = "isUnowned", required = false) Byte isUnowned) {
        try {
            GridCompany wsCompany = new GridCompany();
            wsCompany.setWgCode(wgCode);
            wsCompany.setQylxCode(qylxCode);
            wsCompany.setCreditCode(creditCode);
            wsCompany.setIsClosed(isClosed);
            wsCompany.setIsUnowned(isUnowned);
            PageHelper.startPage(pageNum, pageSize);
            PageInfo<GridCompanyExt> pageInfo = gridCompanyService.page(wsCompany, value);
            return AjaxResult.success(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(500, "服务器内部错误");
        }
    }

    /**
     * 保存
     */
    @PostMapping(value = "/add")
    public AjaxResult add(@RequestBody GridCompany wsCompany) {
        wsCompany.setCreateId(getUserId());
        return gridCompanyService.add(wsCompany);
    }

    /**
     * 修改
     */
    @PostMapping(value = "/edit")
    public AjaxResult edit(@RequestBody GridCompany wsCompany) {
        wsCompany.setUpdateId(getUserId());
        return gridCompanyService.edit(wsCompany);
    }

    /**
     * 详情
     */
    @GetMapping(value = "/detail/{id}")
    public AjaxResult detail(@PathVariable("id") String id) {
        return gridCompanyService.detail(id);
    }

    /**
     * 通过id删除
     */
    @GetMapping(value = "/delete")
    public AjaxResult delete(@RequestParam(value = "id") String id) {
        return gridCompanyService.delete(id);
    }

    /**
     * 通过统一社会信用代码查询详情
     */
    @GetMapping(value = "/detail")
    public AjaxResult detailByCreditCode(@RequestParam(value = "creditCode") String creditCode) {
        return gridCompanyService.detailByCreditCode(creditCode);
    }

    /**
     * 企业所在地块的其他企业
     */
    @GetMapping(value = "/otherCompanyPage")
    public AjaxResult otherCompany(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                   @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                   @RequestParam(value = "creditCode") String creditCode,
                                   @RequestParam(value = "wgCode") String wgCode) {
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<GridCompany> pageInfo = new PageInfo<>(gridCompanyService.otherCompany(creditCode, wgCode));
        return AjaxResult.success(pageInfo);
    }

    /**
     * 企业经济数据
     */
    @GetMapping(value = "/economyPage")
    public AjaxResult economy(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                              @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                              @RequestParam(value = "creditCode") String creditCode,
                              @RequestParam(value = "belongTime", required = false) String belongTime) {
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<GridCompanyEconomy> pageInfo = new PageInfo<>(gridCompanyService.economy(creditCode, belongTime));
        return AjaxResult.success(pageInfo);
    }

    /**
     * 企业关联人口信息
     */
    @GetMapping(value = "/companyToPeoplePage")
    public AjaxResult companyToPeoplePage(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                          @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                          @RequestParam(value = "companyId", required = false) String companyId,
                                          @RequestParam(value = "creditCode", required = false) String creditCode) {
        try {
            PageHelper.startPage(pageNum, pageSize);
            List<GridCompanyPeople> companyPeopleList = gridCompanyPeopleService.selectGridCompanyPeopleByCompanyId(companyId, creditCode, null);
            List<GridCompanyPeopleExt> companyPeopleExtList = BeanCopyUtil.bathToBean(companyPeopleList, GridCompanyPeopleExt.class);
            Map<String, String> regionMap = gridRegionService.getGridRegionMap().stream().collect(Collectors.toMap(GridRegion::getWgCode, GridRegion::getWgName));
            Map<String, String> commonMap = bsCommonService.getBsCommonMap().stream().collect(Collectors.toMap(BsCommon::getCode, BsCommon::getName));
            for (GridCompanyPeopleExt c : companyPeopleExtList) {
                gridCompanyPeopleService.selectGridCompanyPeopleExt(regionMap, commonMap, c, false, true);
            }
            PageInfo<GridCompanyPeopleExt> pageInfo = ZQTPageUtil.build(companyPeopleList, companyPeopleExtList);
            return AjaxResult.success(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(500, "服务器内部错误");
        }
    }

    /**
     * 企业绑定人口信息
     */
    @PostMapping(value = "/companyBindPeople")
    public AjaxResult companyBindPeople(@RequestBody GridCompanyPeople wsCompanyPeople) {
        return gridCompanyService.companyBindPeople(wsCompanyPeople);
    }

    /**
     * 企业解绑人口信息
     */
    @GetMapping(value = "/companyUnbindPeople")
    public AjaxResult companyUnbindPeople(@RequestParam(value = "id") String id) {
        gridCompanyPeopleService.deleteByStringPrimaryKey(id);
        return AjaxResult.success(null);
    }

    /**
     * 企业信息excel导入
     */
    @PostMapping(value = "import", headers = "content-type=multipart/form-data")
    public AjaxResult importExcel(@RequestParam(value = "file") MultipartFile file,
                                  @RequestParam(value = "createId") String createId) {
        return gridCompanyService.importExcel(file, createId);
    }

    @ApiOperation("企业等级枚举")
    @GetMapping("/level/enum")
    public AjaxResult companyLevel(){
        Map<String, String> map = new LinkedHashMap<>();
        map.put(GridCompanyLevelEnum.RED.getCode(), GridCompanyLevelEnum.RED.getValue());
        map.put(GridCompanyLevelEnum.YELLOW.getCode(), GridCompanyLevelEnum.YELLOW.getValue());
        map.put(GridCompanyLevelEnum.GREEN.getCode(), GridCompanyLevelEnum.GREEN.getValue());
        return AjaxResult.success(map);
    }

    @ApiOperation("所有企业列表")
    @GetMapping("/allCompanyList")
    public AjaxResult getCompanyList(@RequestParam(value = "wgCode")String wgCode){
        GridCompanySearchParam param = new GridCompanySearchParam();
        if(StringUtils.isNotBlank(wgCode)){
            param.setWgCodeLikes(Arrays.asList(wgCode.split(",")));
        }
        return AjaxResult.success(gridCompanyService.getAllCompanyList(param));
    }

//    @GetMapping("/saveLabel")
//    public AjaxResult saveLabel(@RequestParam(value = "id")String id,@RequestParam(value = "label")String label){
//        return AjaxResult.success(gridCompanyMapper.insertLabelById(id,label));
//    }
//
//    @GetMapping("/selectLabel")
//    public AjaxResult selectLabel(@RequestParam(value = "id")String id){
//        return AjaxResult.success(gridCompanyMapper.selectLabelById(id));
//    }

    @PostMapping("/saveCompanyLabel")
    public AjaxResult saveCompanyLabel(@RequestBody CompanyLabel companyLabel){
        String id = companyLabel.getId();
        List<CompanyLabelLevelOne> labels = companyLabel.getLabels();
        String strLabel = "";
        for (CompanyLabelLevelOne label : labels) {
            strLabel += label.getLevelTwo()+":"+label.getValue()+",";
        }
        return AjaxResult.success(gridCompanyMapper.insertLabelById(id,strLabel));
    }

    @GetMapping("/selectCompanyLabel")
    public AjaxResult selectCompanyLabel(@RequestParam("id") String id){
        String label = gridCompanyMapper.selectLabelById(id);
        List<CompanyLabelLevelOne> res = new ArrayList<>();
        List<String> labels = Arrays.asList(label.split(","));
        for (String labelTwo : labels) {
            List<String> labelTwos = Arrays.asList(labelTwo.split(":"));
            CompanyLabelLevelOne companyLabel = new CompanyLabelLevelOne();
            companyLabel.setLevelTwo(labelTwos.get(0));
            companyLabel.setValue(labelTwos.get(1));
            res.add(companyLabel);
        }
        return AjaxResult.success(res);
    }

}
