package com.dsk.web.controller.customer;

import cn.hutool.core.bean.BeanException;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpException;
import com.dsk.common.annotation.Log;
import com.dsk.common.annotation.RepeatSubmit;
import com.dsk.common.core.controller.BaseController;
import com.dsk.common.core.domain.AjaxResult;
import com.dsk.common.core.page.TableDataInfo;
import com.dsk.common.enums.BusinessType;
import com.dsk.common.utils.poi.ExcelUtil;
import com.dsk.system.domain.customer.Customer;
import com.dsk.system.domain.customer.dto.CustomerBusinessSearchDto;
import com.dsk.system.domain.customer.dto.CustomerSearchDto;
import com.dsk.system.service.ICustomerService;
import com.dsk.web.controller.search.service.BusinessOpportunityRadarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户相关
 *
 * @author lcl
 * @create 2023/5/16
 */
@RestController
@RequestMapping("/customer")
public class CustomerController extends BaseController {

    @Autowired
    private ICustomerService baseService;
    @Autowired
    private BusinessOpportunityRadarService opportunityRadarService;

    /**
     * 查询客户列表
     */
    @PreAuthorize("@ss.hasPermi('customer:list')")
    @GetMapping("/list")
    public TableDataInfo selectPageList(CustomerSearchDto dto) {
        startPage();
        return getDataTable(baseService.selectList(dto));
    }

    /**
     * 客户详情
     */
    @PreAuthorize("@ss.hasPermi('customer:info')")
    @GetMapping("/{customerId}")
    public AjaxResult info(@PathVariable("customerId") String customerId) {
        return AjaxResult.success(baseService.info(customerId));
    }

    /**
     * 添加客户
     */
    @PreAuthorize("@ss.hasPermi('customer:add')")
    @PostMapping()
    @RepeatSubmit
    public AjaxResult add(@RequestBody Customer customer) {
        dealWithcustomerData(customer);
        return toAjax(baseService.add(customer));
    }

    /**
     * 认领客户
     */
//    @PreAuthorize("@ss.hasPermi('customer:claim')")
    @PostMapping("/claim")
    @RepeatSubmit
    public AjaxResult claim(@RequestBody Customer customer) {
        if (ObjectUtils.isEmpty(customer.getUipId())) throw new BeanException("城投uipId不能为空");
        dealWithcustomerData(customer);
        boolean add = baseService.add(customer);
        if (add) {
            Map<String, Object> map = new HashMap<>();
            map.put("customerId", customer.getCustomerId());
            return AjaxResult.success(map);
        }
        return AjaxResult.error();
    }

    private void dealWithcustomerData(Customer customer) {
        if (ObjectUtils.isEmpty(customer.getCompanyName())) throw new BeanException("企业名称不能为空");
        if (ObjectUtils.isEmpty(customer.getCompanyId())) {
            try {
                Map<String, Object> map = opportunityRadarService.enterpriseByName(customer.getCompanyName());
                if (!ObjectUtils.isEmpty(map.get("data"))) {
                    customer.setCompanyId(MapUtil.getInt(BeanUtil.beanToMap(map.get("data")), "jskEid"));
                    if (ObjectUtils.isEmpty(customer.getLegalPerson())) {
                        customer.setLegalPerson(MapUtil.getStr(map, "legalPerson"));
                    }
                    if (ObjectUtils.isEmpty(customer.getRegisterCapital())) {
                        customer.setRegisterCapital(MapUtil.getStr(map, "registeredCapitalStr"));
                    }
                    if (ObjectUtils.isEmpty(customer.getProvinceId())) {
                        customer.setProvinceId(MapUtil.getInt(map, "provinceId"));
                    }
                    if (ObjectUtils.isEmpty(customer.getCityId())) {
                        customer.setCityId(MapUtil.getInt(map, "cityId"));
                    }
                    if (ObjectUtils.isEmpty(customer.getDistrictId())) {
                        customer.setDistrictId(MapUtil.getInt(map, "countyId"));
                    }
                    if (ObjectUtils.isEmpty(customer.getRegisterAddress())) {
                        customer.setRegisterAddress(MapUtil.getStr(map, "domicile"));
                    }
                    if (ObjectUtils.isEmpty(customer.getCreditCode())) {
                        customer.setCreditCode(MapUtil.getStr(map, "creditCode"));
                    }
                }
            } catch (Exception e) {
                logger.debug("获取企业id错误！error：{}", e.getMessage());
            }
        }
    }



    /**
     * 编辑客户
     */
    @PreAuthorize("@ss.hasPermi('customer:edit')")
    @PutMapping()
    @RepeatSubmit
    public AjaxResult edit(@RequestBody Customer customer) {
        return AjaxResult.success(baseService.edit(customer));
    }

    /**
     * 获取个人客户列表
     */
    @GetMapping("/user/list")
    public AjaxResult userList() {
        return AjaxResult.success(baseService.selectUserList());
    }

    /**
     * 获取客户项目（合作情况）列表
     */
//    @PreAuthorize("@ss.hasPermi('customer:business:list')")
    @GetMapping("/business/list")
    public TableDataInfo businessList(CustomerBusinessSearchDto dto) {
        startPage();
        return getDataTable(baseService.selectBusinessList(dto));
    }

    @Log(title = "客户数据导入", businessType = BusinessType.IMPORT)
    //@PreAuthorize("@ss.hasPermi('customer:importData')")
    @PostMapping("/importData")
    public AjaxResult importData(@RequestPart("file") MultipartFile file) throws Exception {
        List<Customer> customerList = new ExcelUtil<>(Customer.class).importExcel(file.getInputStream(), 2);
        List<String> resultList = new ArrayList<>();
        int successCount = 0;
        for (Customer customer : customerList) {
            if (ObjectUtils.isEmpty(customer.getCompanyName())) {
                continue;
            }
            try {
                Map<String, Object> map = opportunityRadarService.enterpriseByName(customer.getCompanyName());
                if (ObjectUtils.isEmpty(map)) {
                    throw new HttpException("远程调用匹配接口失败！");
                }
                Map<String, Object> obj = BeanUtil.beanToMap(map.get("data"));
                if (!ObjectUtils.isEmpty(obj)) {
                    customer.setCompanyId(MapUtil.getInt(obj, "jskEid"));
                    customer.setLegalPerson(MapUtil.getStr(obj, "legalPerson"));
                    customer.setRegisterCapital(MapUtil.getStr(obj, "registeredCapitalStr"));
                    customer.setProvinceId(MapUtil.getInt(obj, "provinceId"));
                    customer.setCityId(MapUtil.getInt(obj, "cityId"));
                    customer.setDistrictId(MapUtil.getInt(obj, "countyId"));
                    customer.setRegisterAddress(MapUtil.getStr(obj, "domicile"));
                    customer.setCreditCode(MapUtil.getStr(obj, "creditCode"));
                }
                baseService.add(customer);
                successCount++;
            } catch (Exception e) {
                resultList.add(customer.getCompanyName().concat(":").concat(e.getMessage()));
            }
        }
        AjaxResult success = AjaxResult.success(resultList);
        success.put("successCount", successCount);
        return success;
    }

    /**
     * 客户状态
     */
    @GetMapping("/status/{companyName}")
    public AjaxResult status(@PathVariable String companyName) {
        return AjaxResult.success(baseService.status(companyName));
    }


    /**
     * 取消认领
     */
    @PutMapping("/cancelClaim/{companyName}")
    @RepeatSubmit
    public AjaxResult cancelClaim(@PathVariable String companyName) {
        return toAjax(baseService.cancelClaim(companyName));
    }

    /**
     * 历史认领
     */
    @PutMapping("/historyClaim/{companyName}")
    @RepeatSubmit
    public AjaxResult historyClaim(@PathVariable String companyName) {
        return toAjax(baseService.historyClaim(companyName));
    }
}
