package com.sifang.modules.sunshine.SystemSetting.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.dao.ProductLineSetDao;
import com.sifang.modules.sunshine.SystemSetting.entity.ProductLineSet;
import com.sifang.modules.sunshine.SystemSetting.form.FormSetPageVo;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.SystemSetting.vo.GfKcFormVo;
import com.sifang.modules.sunshine.SystemSetting.vo.RoofSetFormVo;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.FormPartnerSet;
import com.sifang.modules.sys.common.entity.FormSet;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.dao.FormPartnerSetDao;
import com.sifang.modules.sys.dao.FormSetDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class FormSetService extends BaseService {

    @Autowired
    private ProductLineSetDao dao;

    @Autowired
    private FormSetDao formSetDao;

    @Autowired
    private FormPartnerSetDao partnerSetDao;

    /**
     * 获取设置列表
     */
    public List<Record> getList(Map<String, String> params) {
        return dao.findList(params);
    }

    /**
     * 查询变更类型设置详情
     */
    public Record getOneById(String id) {
        return dao.findOneById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public Result add(String name, String attribute,  Result result) {
        // 校验名称
        long total = dao.queryCountByName(name, null);
        if (total > 0) {
            result.setCode("206");
            result.setMsg("已存在相同类型名称，请重新设置");
            return result;
        }
        User user = UserUtils.getUser();
        ProductLineSet set = new ProductLineSet();
        set.setName(name);
        set.setAttribute(attribute);
        set.setCreateBy(user.getId());
        set.setCreateTime(new Date());
        dao.save(set);
        result.setCode("200");
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result edit(String id, String name, String attribute,  Result result) {
        // 校验名称
        long total = dao.queryCountByName(name, id);
        if (total > 0) {
            result.setCode("206");
            result.setMsg("已存在相同类型名称，请重新设置");
            return result;
        }
        ProductLineSet set = dao.get(id);
        set.setName(name);
        set.setAttribute(attribute);
        set.setUpdateTime(new Date());
        dao.save(set);
        result.setCode("200");
        return result;
    }

    public void deleteById(String id) {
        dao.deleteById(id);
    }

    /**
     * 是否启用
     */
    public Result changeUseFlag(String id, String partner, String attr) {
        // 必填字段不能禁用
        FormSet formSet = formSetDao.get(id);
        if (formSet == null) {
            return Result.fail("未查询到设置信息");
        } else if (Objects.equals("1", formSet.getMustFillFlag())
                && Objects.equals("0", attr)) {
            return Result.fail("必填字段不能禁用");
        }
        FormPartnerSet partnerSet = partnerSetDao.findOneByFormSetId(id, partner);
        if (partnerSet == null) {
            partnerSetDao.createOne(formSet.getId(), partner, formSet.getMustFillFlag(), attr);
        } else {
            partnerSet.setStatus(attr);
        }
        return Result.ok();
    }

    /**
     * 是否必填
     */
    public Result changeMustFillFlag(String id, String partner, String attr) {
        FormSet formSet = formSetDao.get(id);
        if (formSet == null) {
            return Result.fail("未查询到设置信息");
        } else if (Objects.equals("1", formSet.getMustFillFlag())
                && Objects.equals("0", attr)) {
            return Result.fail("必填字段不能修改");
        }
        FormPartnerSet partnerSet = partnerSetDao.findOneByFormSetId(id, partner);
        if (partnerSet == null) {
            partnerSetDao.createOne(formSet.getId(), partner, attr, "0");
        } else {
            partnerSet.setMustFillFlag(attr);
        }
        return Result.ok();
    }

    /**
     * 处理获取的表单设置
     */
    public Record getListByCondition(String stage, String partner) {
        return getListByCondition(stage,partner,null);
    }

    /**
     * 处理获取的表单设置
     */
    public Record getListByCondition(String stage, String partner, String groupType) {
        List<Record> list = formSetDao.findListByCondition(stage, partner, groupType);
        Record record = new Record();
        // 处理表单设置数据
        for (Record r : list) {
            FormSetPageVo vo = new FormSetPageVo();
            if (Objects.equals("1", r.getStr("parentMustFillFlag"))
                    || Objects.equals("1", r.getStr("limitFlag"))) {
                vo.setMustFillFlag("1");
                vo.setStatus("1");
            } else if (StringUtil.isBlank(r.getStr("id"))) {
                vo.setMustFillFlag(r.getStr("parentMustFillFlag"));
                vo.setStatus("0");
            } else {
                vo.setMustFillFlag(r.getStr("mustFillFlag"));
                vo.setStatus(r.getStr("status"));
            }
            vo.setSampleGraph(r.getStr("sampleGraph"));
            vo.setColumnType(r.getStr("columnType"));
            record.set(r.getStr("columnKey"), vo);
        }
        return record;
    }

    /**
     * 处理获取的表单设置
     */
    public Map getAllConditionList(String partner) {
        List<String> strList = Arrays.asList("01","02","03","04","05");
        Map<String, Object> map = new HashMap<>();
        for(String s :strList){
            map.put(s, getAllListByCondition(s, partner,null));
        }
        return map;
    }

    public Map getAllListByCondition(String stage, String partner, String groupType) {
        List<Record> list = formSetDao.findListByCondition(stage, partner, groupType);
        Map<String, Object> map =new HashMap<>();
        // 处理表单设置数据
        for (Record r : list) {
            FormSetPageVo vo = new FormSetPageVo();
            if (Objects.equals("1", r.getStr("parentMustFillFlag"))
                    || Objects.equals("1", r.getStr("limitFlag"))) {
                vo.setMustFillFlag("1");
                vo.setStatus("1");
            } else if (StringUtil.isBlank(r.getStr("id"))) {
                vo.setMustFillFlag(r.getStr("parentMustFillFlag"));
                vo.setStatus("0");
            } else {
                vo.setMustFillFlag(r.getStr("mustFillFlag"));
                vo.setStatus(r.getStr("status"));
            }
            vo.setSampleGraph(r.getStr("sampleGraph"));
            vo.setColumnType(r.getStr("columnType"));
            map.put(r.getStr("columnKey"),vo);
        }
        return map;
    }

    //获取表单必填字段
    public List<String> getMustFillFlag(String stage, String partnerId){
        StringBuilder sb=new StringBuilder();
        sb.append(" SELECT s.column_key AS column_key FROM `crm_form_partner_set` ps  ");
        sb.append(" LEFT JOIN `crm_form_set` s ON s.id=ps.`form_set_id` ");
        sb.append(" WHERE ps.`partner`=? AND s.stage=? AND (s.must_fill_flag='1' OR ps.must_fill_flag='1')  ");
        List<String> list = Db.query(sb.toString(),partnerId,stage);
        if (list == null) {
            list = new ArrayList<>();
        }
        return list;
    }


    //获取广发勘测阶段不同屋顶类型对应字段
    public static List<RoofSetFormVo> getGfFormSetByRoofType(){
       List<Record> list=Db.find(" SELECT roof_type,column_type,column_key,column_name,must_fill_flag FROM `crm_roof_type_from_set` ORDER BY roof_type,sort  ");
       Map<String, List<Record>> itemMap = list.stream().collect(Collectors.groupingBy(r -> r.getStr("roof_type")));
       List<RoofSetFormVo> resultList=new ArrayList<>();
       for(Map.Entry<String,List<Record>> r:itemMap.entrySet()){
           String key=r.getKey();
           List<Record> value=r.getValue();

          String need=value.stream().filter(v -> v.getStr("must_fill_flag").equals("1")).map(e -> e.getStr("column_key")).collect(Collectors.joining(","));
           String all=value.stream().map(e -> e.getStr("column_key")).collect(Collectors.joining(","));
           RoofSetFormVo vo=new RoofSetFormVo();
           vo.setRoofType(key);
           vo.setNotEmptyStr(need);
           vo.setNeedFormStr(all);
           resultList.add(vo);
       }
       return resultList;
    }

    //根据广发的屋顶类型，获取必填项
    public static String getNotEmptyForm(String roofType){
        return Db.queryStr("  SELECT GROUP_CONCAT(column_key)  FROM `crm_roof_type_from_set` WHERE roof_type=? AND must_fill_flag='1' ",roofType);
    }

    //根据广发勘测阶段不同屋顶类型，对应不同字段
    public static List<GfKcFormVo> getGfFormSetKc(){
        List<Record> list=Db.find(" SELECT roof_type,column_type,column_key,column_name,must_fill_flag FROM `crm_roof_type_from_set` ORDER BY roof_type,sort  ");
        Map<String, List<Record>> itemMap = list.stream().collect(Collectors.groupingBy(r -> r.getStr("roof_type")));
        List<GfKcFormVo> formVos=new ArrayList<>();
        for(Map.Entry<String,List<Record>> r:itemMap.entrySet()){
            String key=r.getKey();
            List<Record> value=r.getValue();
            GfKcFormVo formVo=new GfKcFormVo(key,value);
            formVos.add(formVo);
        }
        return formVos;
    }

}
