package cn.ezhizao.project.business.company.controller;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.ezhizao.common.utils.StringUtils;
import cn.ezhizao.project.business.channel.domain.BizChannel;
import cn.ezhizao.project.business.channel.service.IBizChannelService;
import cn.ezhizao.project.business.company.domain.DictRegion;
import cn.ezhizao.project.business.company.domain.vo.Region;
import cn.ezhizao.project.business.company.service.IDictRegionService;
import cn.ezhizao.project.business.company.service.impl.BizCompanyServiceImpl;
import cn.ezhizao.project.business.companyContactor.domain.BizCompanyContactor;
import cn.ezhizao.project.business.companyContactor.service.IBizCompanyContactorService;
import cn.ezhizao.project.business.companyFollow.domain.BizCompanyFollowDetail;
import cn.ezhizao.project.business.companyFollow.service.IBizCompanyFollowDetailService;
import cn.ezhizao.project.system.domain.SysUser;
import cn.ezhizao.project.system.service.ISysUserService;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.schema.ArraySchema;
import org.apache.commons.io.IOUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.project.business.company.domain.BizCompany;
import cn.ezhizao.project.business.company.service.IBizCompanyService;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import cn.ezhizao.framework.web.controller.BaseController;

/**
 * companyController
 *
 * @author ezhizao
 * @date 2023-10-16
 */
@RestController
@RequestMapping("/business/company")
public class BizCompanyController extends BaseController
{
    @Resource
    private IBizCompanyService bizCompanyService;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private IBizChannelService bizChannelService;
    @Resource
    private IBizCompanyContactorService bizCompanyContactorService;
    @Resource
    private IDictRegionService dictRegionService;
    @Resource
    private IBizCompanyFollowDetailService companyFollowDetailService;

    /**
     * 查询company列表
     */
    @PreAuthorize("@ss.hasPermi('business:company:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizCompany bizCompany) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizCompany);
        startPage();
        startOrderBy();
        List<BizCompany> list = bizCompanyService.getList(bizCompany);
        return getDataTable(list);
    }

    /**
     * 导出company列表
     */
    @PreAuthorize("@ss.hasPermi('business:company:export')")
    @Log(title = "company", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizCompany bizCompany) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizCompany);
        List<BizCompany> list = bizCompanyService.getList(bizCompany);
        ExcelUtil<BizCompany> util = new ExcelUtil<BizCompany>(BizCompany.class);
        if (bizCompany.getColumns() != null && !bizCompany.getColumns().isEmpty()) {
            util.exportExcel(response, list, "company数据", "客户信息导出", bizCompany.getColumns().toArray(new String[0]));
        } else {
            util.exportExcel(response, list, "company数据", "客户信息导出");
        }
    }

    @Log(title = "客户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('business:company:add')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception
    {
        ExcelUtil<BizCompany> util = new ExcelUtil<>(BizCompany.class);
        List<BizCompany> companyList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = bizCompanyService.importCompany(companyList, operName, getTenantId() == null ? 0 : getTenantId());
        return success(message);
    }

    /**
     * 获取company详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:company:info')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        BizCompany bizCompany = new BizCompany();
        bizCompany.setId(id);
        List<BizCompany> bizCompanyList = bizCompanyService.getList(bizCompany);
        bizCompany = bizCompanyList.size() > 0 ? bizCompanyList.get(0) : null;
        if(bizCompany != null && bizCompany.getReferrerDataSource() != null) {
            switch (bizCompany.getReferrerDataSource()) {
                case "company":
                    BizCompany source = bizCompanyService.getById(bizCompany.getSourceId());
                    bizCompany.setSourceName(source != null ? source.getName() : "");
                    break;
                case "employee":
                    SysUser sysUser = sysUserService.selectUserById(bizCompany.getSourceId());
                    bizCompany.setSourceName(sysUser != null ? sysUser.getNickName() : "");
                    break;
                case "channel":
                    BizChannel channel = bizChannelService.getById(bizCompany.getSourceId());
                    bizCompany.setSourceName(channel != null ? channel.getName() : "");
                    break;
                default:
                    break;
            }
        }
        if (bizCompany != null) {
            BizCompanyContactor condition = new BizCompanyContactor();
            condition.setCompanyId(bizCompany.getId());
            bizCompany.setContactors(bizCompanyContactorService.getList(condition));
            BizCompanyFollowDetail followDetail = new BizCompanyFollowDetail();
            followDetail.setCompanyId(bizCompany.getId());
            List<BizCompanyFollowDetail> followDetails = companyFollowDetailService.getList(followDetail);
            bizCompany.setFollowDetails(followDetails);
        }
        return success(bizCompany);
    }

    /**
     * 新增company
     */
    @PreAuthorize("@ss.hasPermi('business:company:add')")
    @Log(title = "company", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizCompany bizCompany) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizCompany);

        return bizCompanyService.save(bizCompany) ? success("保存成功", bizCompany)  : error("保存失败");
    }

    /**
     * 修改company
     */
    @PreAuthorize("@ss.hasPermi('business:company:edit')")
    @Log(title = "company", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizCompany bizCompany) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizCompany);
        return bizCompanyService.updateById(bizCompany) ? success("保存成功", bizCompany) : error("保存失败");
    }

    /**
     * 删除company
     */
    @PreAuthorize("@ss.hasPermi('business:company:remove')")
    @Log(title = "company", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids)
    {
        return toAjax(bizCompanyService.removeBatchByIds(ids));
    }

    /**
     * 导出初始化客户模板
     * @param response
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<BizCompany> util = new ExcelUtil<>(BizCompany.class);
        util.importTemplateExcel(response, "客户数据", StringUtils.EMPTY, new String[]{"name", "sourceCategoryName", "sourceName"});
    }

    @PostMapping("/setCompanyAdviser")
    @PreAuthorize("@ss.hasPermi('business:company:edit')")
    @Log(title = "company", businessType = BusinessType.UPDATE)
    public AjaxResult setCompanyAdviser(@RequestBody BizCompany company) {
        List<Long> ids = company.getIds();
        Long adviserId = company.getAdviserId();
        BizCompany conditions = new BizCompany();
        conditions.setIds(ids);
        List<BizCompany> companies = bizCompanyService.getList(conditions);
        companies.forEach(l -> l.setAdviserId(adviserId));
        return toAjax(bizCompanyService.updateBatchById(companies));
    }

    @PostMapping("/setCompanyLeader")
    @PreAuthorize("@ss.hasPermi('business:company:edit')")
    @Log(title = "company", businessType = BusinessType.UPDATE)
    public AjaxResult setCompanyLeader(@RequestBody BizCompany company) {
        List<Long> ids = company.getIds();
        Long leaderId = company.getLeaderId();
        BizCompany conditions = new BizCompany();
        conditions.setIds(ids);
        List<BizCompany> companies = bizCompanyService.getList(conditions);
        companies.forEach(l -> l.setLeaderId(leaderId));
        return toAjax(bizCompanyService.updateBatchById(companies));
    }

    @GetMapping(value = "/initArea")
    @PreAuthorize("@ss.hasPermi('business:company:list')")
    public AjaxResult initArea()  throws IOException {
        List<DictRegion> regions = JSONArray.parseArray(IOUtils.toString(BizCompanyServiceImpl.class.getResourceAsStream("/company/region.json"), Charset.forName("UTF-8")), DictRegion.class);
//        dictRegionService.saveBatch(regions)
        return success(regions);
    }


}
