/**
 * 走访管理后台
 */
import moment = require("moment");
import { RESEARCHTYPE, VISITENTERPRISETYPE } from "../../../config/enum";
import * as visitData from "../../../data/fuHuaQi/visit";
import { changeEnumValue } from "../../../util/verificationEnum";
import { BizError } from "../../../util/bizError";
import { ERRORENUM } from "../../../config/errorEnum";


export async function trackList(name, type, state, page) {
    let param:any = {follow:true};
    if (name) param.name = {"$regex":name};
    if (type) param.enterpriseType = type;
    if (state) param.state = state;

    let dbList = await visitData.findPageByParam(param, (page-1)*10);
    let count = visitData.findCountByParam(param);

    let dataList = [];
    dbList.forEach(info => {
        let stateStr = "待走访";
        if (info.state == 2) stateStr = "取消走访";
        else if (info.state == 3) stateStr = "完成走访";
        let item = {
            id:info.id, 
            uscc:info.uscc, 
            name:info.enterpriseName,
            trackType:changeEnumValue(VISITENTERPRISETYPE, info.enterpriseType), 
            trackState:stateStr, 
            trackTime:moment(info.visitTime).format("YYYY-MM-DD"), 
            completionTime:"-"//这里小程序走访完成的时候不会记录时间
        };
        dataList.push(item);
    })

    return {dataList, count}
}

export async function deleteTrack(id) {
    let trackInfo = await visitData.findOne({id});
    if (!trackInfo || !trackInfo.id) throw new BizError(ERRORENUM.目标数据不存在);

    await visitData.removeOneData(id);

    return {isSuccess:true};
}

export async function changeTrackState(id, state) {
    let trackInfo = await visitData.findOne({id});
    if (!trackInfo || !trackInfo.id) throw new BizError(ERRORENUM.目标数据不存在);

    trackInfo.state = state;
 
    return {isSuccess:true};
}

export async function trackInfo(uscc) {
    let trackInfo = await visitData.findOne({uscc});
    if (!trackInfo || !trackInfo.id) throw new BizError(ERRORENUM.目标数据不存在);

    let dataInfo = {
        name:trackInfo.enterpriseName, 
        trackType:changeEnumValue(VISITENTERPRISETYPE, trackInfo.enterpriseType), 
        trackTime:moment(trackInfo.visitTime).format("YYYY-MM-DD"), 
        accompany:trackInfo.accompany, 
        leaderName:trackInfo.leaderName,
        researchType:changeEnumValue(RESEARCHTYPE, trackInfo.researchType), 
        desc:trackInfo.desc
    }

    return {dataInfo}
}