const system = require("../../../system");
const ServiceBase = require("../../sve.base")
/**
 * 订单产品表
 */
class CclueService extends ServiceBase {
    constructor() {
        super("chance", ServiceBase.getDaoName(CclueService));
        this.cschemeDao = system.getObject("db.chance.cschemeDao");
        this.cfollowlogDao = system.getObject("db.chance.cfollowlogDao");
    }

    /**
     * fn:保存线索
     * @param params
     * @returns {Promise<void>}
     */
    async saveClue(params){
        if(!params.clue_type_id){
            return system.getResult(null, `参数错误 产品ID不能为空`);
        }
        if(!params.clue_type_name){
            return system.getResult(null, `参数错误 产品名称不能为空`);
        }
        if(!params.deliver_id){
            return system.getResult(null, `参数错误 交付商ID不能为空`);
        }
        let clue_properties = {
            clue_type_id : this.trim(params.clue_type_id),
            clue_type_name : this.trim(params.clue_type_name),
            contacts : this.trim(params.contacts),
            contact_mobile:this.trim(params.contact_mobile),
            operator_id:this.trim(params.operator_id),
            operator_path : this.trim(params.operator_path),
            callback_url : this.trim(params.callback_url),
            status:"10",
            deliver_id:this.trim(params.deliver_id),
            clue_content:this.trim(params.clue_content)||""
        };
        try{
            await this.db.transaction(async t =>{
                let cclueBean =await this.dao.create(clue_properties, t);
                let scheme_properties = {
                    id:cclueBean.id,
                    clue_type_name:clue_properties.clue_type_name,
                    deliver_id:clue_properties.deliver_id,
                    legal_name : clue_properties.contacts,
                    legal_mobile:clue_properties.contact_mobile,
                };
                await this.cschemeDao.create(scheme_properties,t);
            });
            return system.getResultSuccess();
        }catch (e) {
            console.log(e);
            return system.getResult(null, `系统错误`);
        }
    }

    /**
     * fn:关闭线索
     * @param params
     * @returns {Promise<void>}
     */
    async closeClue(params){
        if(!params.id){
            return system.getResult(null, `参数错误 ID不能为空`);
        }
        if(!params.deliver_id){
            return system.getResult(null, `参数错误 交付商ID不能为空`);
        }
        if(!params.close_reason){
            return system.getResult(null, `参数错误 关闭原因不能为空`);
        }
        if(params.close_reason=="50" && !params.close_remarks){
            return system.getResult(null, `参数错误 关闭原因不能为空`);
        }
        let _cclue = await this.dao.model.findOne({
            where:{
                id: this.trim(params.id),
                deliver_id: this.trim(params.deliver_id)
            },
            attributes:['id','status','callback_url']
        });
        if(!_cclue){
            return system.getResult(null, `线索不存在`);
        }
        if(_cclue.status=='30'){
            return system.getResult(null, `线索已完成`);
        }
        if(_cclue.status=='40'){
            return system.getResult(null, `线索已关闭`);
        }
        let upd = {
            id: this.trim(params.id),
            close_reason: this.trim(params.close_reason),
            close_remarks: this.trim(params.close_remarks) || "",
            status:"40"
        };
        try{
            let res = await this.update(upd);
            return system.getResult({id:_cclue.id,callback_url:_cclue.callback_url});
        }catch (e) {
            console.log(e);
            system.getResult(null, `系统错误`);
        }
    }

    /**
     * fn:线索列表
     * @param params
     * @returns {Promise<void>}
     */
    async listClue(params){
        if(!params.deliver_id){
            return system.getResult(null, `参数错误 交付商不存在`);
        }
        params.currentPage = Number(params.currentPage || 1);
        params.pageSize = Number(params.pageSize || 10);
        params.startRow = (params.currentPage - 1) * params.pageSize;
        try{
            let countRes = await this.dao.countClue(params);
            if(countRes.count==0){
                return system.getResult({count: 0, rows: []});
            }
            let list =await this.dao.listClue(params);
            let clueIds = [];
            for(let element of list) {
                this.handleDate(element, ["created_at"], null, null);
                //线索状态 10 待跟进 20 跟进中 30 已完成 40 已关闭
                if(element.status=='10'){
                    element.status_name = "待跟进";
                }else if(element.status=='20'){
                    element.status_name = "跟进中";
                }else if(element.status=='30'){
                    element.status_name = "已完成";
                }else if(element.status=='40'){
                    element.status_name = "已关闭";
                }else{
                    element.status_name = "";
                }

                //关闭原因 10 客户无意向 20 客户联系不上 30 客户暂时不需要 40 客户已购买其他家 50 其他
                if(element.close_reason=='10'){
                    element.close_reason_name = "客户无意向";
                }else if(element.close_reason=='20'){
                    element.close_reason_name = "客户联系不上";
                }else if(element.close_reason=='30'){
                    element.close_reason_name = "客户暂时不需要";
                }else if(element.close_reason=='40'){
                    element.close_reason_name = "客户已购买其他家";
                }else{
                    element.close_reason_name = "其他";
                }
                clueIds.push(element.id);
            }
            await this.formatCscheme(list, clueIds);
            await this.formatCfollowLog(list, clueIds);
            return system.getResult({count:countRes.count,rows:list});
        }catch (e) {
            console.log(e);
            return system.getResult(null, `系统错误`);
        }
    }

    /**
     * fn:格式化跟踪记录
     * @param list
     * @returns {Promise<void>}
     */
    async formatCfollowLog(list,clueIds){
        if(!list || list.length<=0){
            return ;
        }
        let cschemeMap={},cschemeArrayList=[];
        if(clueIds && clueIds.length>0){
            cschemeArrayList = await this.cfollowlogDao.listFollowlogsByClueIds({clueIds:clueIds});
            for (let item of cschemeArrayList) {
                this.handleDate(item, ["created_at","follow_date"], null, null);
                if(!cschemeMap[item.clue_id]){
                    cschemeMap[item.clue_id]=[];
                }
                cschemeMap[item.clue_id].push(item);
            }
        }
        for (let ele of list) {
            ele.cfollowlog = cschemeMap[ele.id] || [];
            ele.cfollowlogIsShow =ele.cfollowlog.length>0?true:false;
        }
    }

    /**
     * fn:格式化方案
     * @param list
     * @returns {Promise<void>}
     */
    async formatCscheme(list,clueIds){
        if(!list || list.length<=0){
            return ;
        }
        let map = {}, listCscheme=[];
        if(clueIds && clueIds.length>0){
            listCscheme = await this.cschemeDao.cschemes({ids:clueIds});
            for (let item of listCscheme) {
                this.handleDate(item, ["created_at"], null, null);
                map[item.id]=item;
            }
        }
        for (let ele of list) {
            ele.cscheme = map[ele.id];
            if(ele.cscheme.name && ele.status=='40'){
                ele.cschemeIsShow =false;
            }else{
                ele.cschemeIsShow=true;
            }
        }
    }

    /**
     * fn:线索状态列表  10 待跟进 20 跟进中 30 已完成 40 已关闭
     * @returns {Promise<void>}
     */
    async clueStatusDict(){
        let res = [
            {id:"10",name:"待跟进"},
            {id:"20",name:"跟进中"},
            {id:"30",name:"已完成"},
            {id:"40",name:"已关闭"}
        ];
        return system.getResult(res)
    }

    /**
     * fn:线索关闭状态字典  10 客户无意向 20 客户联系不上 30 客户暂时不需要 40 客户已购买其他家 50 其他
     * @returns {Promise<void>}
     */
    async closeReasonDict(){
        let res = [
            {id:"10",name:"客户无意向"},
            {id:"20",name:"客户联系不上"},
            {id:"30",name:"客户暂时不需要"},
            {id:"40",name:"客户已购买其他家"},
            {id:"50",name:"其他"},
        ];
        return system.getResult(res)
    }

    /**
     * fn:根据ID查询详细信息
     * @returns {Promise<void>}
     */
    async getClueById(params){
        if(!params.id){
            return system.getResult(null, `参数错误 ID不能为空`);
        }
        if(!params.deliver_id){
            return system.getResult(null, `参数错误 交付商ID不能为空`);
        }
        try{
            let cclueBean = await  this.dao.getCclueInfo({
                deliver_id:this.trim(params.deliver_id),
                id:this.trim(params.id)
            });
            if(!cclueBean){
                return system.getResult(null, `线索不存在`);
            }
            this.handleDate(cclueBean, ["created_at"], null, null);
            //查询方案
            let cschemeBean = await this.cschemeDao.getById(cclueBean.id) || {};
            this.handleDate(cschemeBean, ["created_at"], null, null);
            cclueBean.cscheme = cschemeBean;
            cclueBean.cschemeIsShow=cschemeBean.name?true:false;

            //查询跟踪记录
            let cfollowlog = await this.cfollowlogDao.listFollowlogsByClueIds({clue_id:cschemeBean.id});
            for(let item of cfollowlog){
                this.handleDate(item, ["created_at","follow_date"], null, null);
            }
            cclueBean.cfollowlog=cfollowlog||[];
            cclueBean.cfollowlogIsShow =cclueBean.cfollowlog.length>0?true:false;
            return system.getResult(cclueBean);
        }catch (e) {
            console.log(e);
            return system.getResult(null, `系统错误`);
        }
    }
}

module.exports = CclueService;