package cn.gtmap.estateplat.config.web.valite;

import cn.gtmap.estateplat.config.core.log.BdcLog;
import cn.gtmap.estateplat.config.core.service.*;
import cn.gtmap.estateplat.config.utils.PlatformUtil;
import cn.gtmap.estateplat.config.web.main.BaseController;
import cn.gtmap.estateplat.core.support.mybatis.mapper.EntityMapper;
import cn.gtmap.estateplat.core.support.mybatis.mapper.Example;
import cn.gtmap.estateplat.core.support.mybatis.page.model.Page;
import cn.gtmap.estateplat.core.support.mybatis.page.repository.Repo;
import cn.gtmap.estateplat.model.server.core.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gtis.common.util.UUIDGenerator;
import com.gtis.plat.vo.PfWorkFlowDefineVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

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

/**
 * @version 1.0, 2017/6/27.
 * @auto <a href="mailto:zhouwanqing@gtmap.cn">zhouwanqing</a>
 * @description
 */
@Controller
@RequestMapping(value = "bdcXtLimitFieldConfig")
public class BdcXtLimitFieldConfigController extends BaseController {

    @Autowired
    PlatformUtil platformUtil;
    @Autowired
    BdcZdGlService bdcZdGlService;
    @Autowired
    EntityMapper entityMapper;
    @Autowired
    WorkFlowService workFlowService;
    @Autowired
    TableService tableService;
    @Autowired
    Repo repository;
    @Autowired
    BdcXtLimitfieldService bdcXtLimitfieldService;
    @Autowired
    BdcRelService bdcRelService;

    @RequestMapping(value = "")
    public String toLimitFieldConfig(Model model) {
        List<PfWorkFlowDefineVo> workFlowList = PlatformUtil.getWorkFlowDefineService().getWorkFlowDefineList();
        List<BdcZdTables> list = bdcZdGlService.getBdcZdTableList();
        //zwq 取所有的qllx
        List<BdcZdQllx> qllxList = bdcZdGlService.getBdcZdQllxList();
        model.addAttribute("workFlowList", workFlowList);
        model.addAttribute("zdTableList", list);
        model.addAttribute("qllxList", qllxList);
        return "valite/bdcXtLimitField";
    }

    //根据工作流查询登记子项
    @ResponseBody
    @RequestMapping("/getBdcZdDjzxBySqlxDm")
    public List<BdcZdDjzx> getBdcZdDjzxBySqlxDm(String workflowId) {
        List<BdcZdDjzx> bdcZdDjzxList = null;
        if (StringUtils.isNotBlank(workflowId)) {
            String sqlxdm = bdcZdGlService.getBdcSqlxdmByWdid(workflowId);
            if(StringUtils.isNotBlank(sqlxdm)) {
                List<BdcSqlxDjzxRel> bdcSqlxDjzxRelList = bdcRelService.getDjzxDmBySqlxDm(sqlxdm);
                if (CollectionUtils.isNotEmpty(bdcSqlxDjzxRelList)) {
                    bdcZdDjzxList = new ArrayList<BdcZdDjzx>();
                    for (BdcSqlxDjzxRel bdcSqlxDjzxRel : bdcSqlxDjzxRelList) {
                        BdcZdDjzx bdcZdDjzx1 = bdcZdGlService.getBdcZdDjzxByDjzxdm(bdcSqlxDjzxRel.getDjzxdm());
                        if (bdcZdDjzx1 != null) {
                            BdcZdDjzx bdcZdDjzx = new BdcZdDjzx();
                            bdcZdDjzx.setDm(bdcSqlxDjzxRel.getDjzxdm());
                            bdcZdDjzx.setMc(bdcZdDjzx1.getMc());
                            bdcZdDjzxList.add(bdcZdDjzx);
                        }
                    }
                }
            }
        }
        return bdcZdDjzxList;
    }

    //获取所有登记子项
    @ResponseBody
    @RequestMapping("/getAllDjzxLx")
    public List<BdcZdDjzx> getAllDjzxlx(){
        Example example = new Example(BdcZdDjzx.class);
        List<BdcZdDjzx> bdcZdDjzxList = entityMapper.selectByExample(example);
        return bdcZdDjzxList;
    }

    @ResponseBody
    @RequestMapping("/getLimitFieldPagesJson")
    public Object getLimitFieldPagesJson(Pageable pageable, String sidx, String sord, BdcXtLimitfield bdcXtLimitfield) {
        Page<HashMap> dataPaging = repository.selectPaging("getLimitFieldByPage", bdcXtLimitfield, pageable);
        return dataPaging;
    }

    //添加限制字段
    @ResponseBody
    @RequestMapping(value = "saveLimitField")
    @BdcLog(controller = "保存必填项验证配置日志",parmjson = "保存必填项验证配置")
    public HashMap saveLimitField(Model model, BdcXtLimitfield bdcXtLimitfield) {
        HashMap map = new HashMap();
        String result = "保存成功";
        try {
            if (StringUtils.isNotBlank(bdcXtLimitfield.getId())) {
                entityMapper.updateByPrimaryKeyNull(bdcXtLimitfield);
            } else {
                bdcXtLimitfield.setId(UUIDGenerator.generate18());
                entityMapper.insertSelective(bdcXtLimitfield);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = "保存失败";
        }
        map.put("result", result);
        return map;
    }

    //删除限制字段
    @ResponseBody
    @RequestMapping("/delLimitFieldConfig")
    @BdcLog(controller = "删除必填项验证配置日志",parmjson = "删除必填项验证配置")
    public HashMap delLimitFieldConfig(Model model, String ids) {
        HashMap map = new HashMap();
        String result = "删除成功！";
        try {
            String id[] = ids.split(",");
            for (int i = 0; i < id.length; i++) {
                entityMapper.deleteByPrimaryKey(BdcXtLimitfield.class, id[i]);
            }
        } catch (Exception e) {
            result = "删除失败！";
            e.printStackTrace();
        } finally {
            map.put("result", result);
        }
        return map;
    }

    //删除限制字段
    @ResponseBody
    @RequestMapping("/delTableConfig")
    @BdcLog(controller = "删除必填项验证表配置日志",parmjson = "删除必填项验证表配置")
    public HashMap delTableConfig(Model model, String ids) {
        HashMap map = new HashMap();
        String result = "删除成功！";
        try {
            String id[] = ids.split(",");
            for (int i = 0; i < id.length; i++) {
                entityMapper.deleteByPrimaryKey(BdcZdTables.class, id[i]);
            }
        } catch (Exception e) {
            result = "删除失败！";
            e.printStackTrace();
        } finally {
            map.put("result", result);
        }
        return map;
    }

    //获取验证节点
    @ResponseBody
    @RequestMapping("/getWorkFlowNodes")
    public List<HashMap> getWorkFlowNodes(Model model, String workflowId) {
        List<HashMap> hashMapList = null;
        if (StringUtils.isNotBlank(workflowId))
            hashMapList = workFlowService.getWorkFlowNodes(workflowId);
        return hashMapList;
    }

    //获取验证table的字典表数据
    @ResponseBody
    @RequestMapping("/getFields")
    public List<HashMap> getFields(Model model, String workFlowId, String workFlowNodeid, String id, @RequestParam(value = "cptName", required = false) String cptName) {
        List<HashMap> hashMapList = null;
        if (StringUtils.isNotBlank(id)) {
            hashMapList = bdcZdGlService.getFields(id);
        }
        return hashMapList;
    }

    /**
     * 获取验证table的字典表数据
     *
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping("/getZdTable")
    public List<BdcZdTables> getZdTable(Model model, String workflowId) {
        List<BdcZdTables> list = bdcZdGlService.getBdcZdTableList();
        return list;
    }

    /**
     * 跳转必填字段表格配置页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/bdcZdTables")
    public String toZdLimitTableConfig(Model model, boolean selTable) {
        List<BdcZdTables> list = bdcZdGlService.getBdcZdTableList();
        model.addAttribute("BdcZdTableList", list);
        model.addAttribute("isSelect", selTable);
        return "valite/bdcZdTables";
    }

    /**
     * 保存必填字段表格配置页面
     *
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "saveLimitTable")
    @BdcLog(controller = "保存必填项验证表配置日志",parmjson = "保存必填项验证表配置")
    public HashMap saveLimitTable(Model model, BdcZdTables bdcZdTables) {
        HashMap map = new HashMap();
        String result = "保存成功";
        try {
            if (StringUtils.isBlank(bdcZdTables.getId()))
                bdcZdTables.setId(UUIDGenerator.generate18());
            entityMapper.saveOrUpdate(bdcZdTables, bdcZdTables.getId());
        } catch (Exception e) {
            e.printStackTrace();
            result = "保存失败";
        }
        map.put("result", result);
        return map;
    }

    //验证字段
    @ResponseBody
    @RequestMapping("/validateSql")
    public HashMap validateSql(Model model, String sqls) {
        HashMap map = new HashMap();
        boolean result = true;
        int num = 1;
        try {
            if (StringUtils.isNotBlank(sqls)) {
                String[] sql = sqls.split(";|；");
                for (int i = 0; i < sql.length; i++) {
                    if (StringUtils.isNotBlank(sql[i])) {
                        sql[i] = sql[i].replaceAll("(?i)@proid", "'test'");
                        tableService.runSql(platformUtil.initOptProperties(sql[i]));
                        num += 1;
                    }
                }
            }
        } catch (Exception e) {
            result = false;
        } finally {
            map.put("result", result);
            map.put("msg", "第" + num + "条sql语句错误！");
        }
        return map;
    }

    //获取必填字段列表
    @ResponseBody
    @RequestMapping("/getBdcLimitTableConfigPagesJson")
    public Object getBdcLimitTableConfigPagesJson(Pageable pageable, String id) {
        HashMap<String, String> map = new HashMap<String, String>();
        if (StringUtils.isNotBlank(id))
            map.put("tableName", "%" + id + "%");
        Page<HashMap> dataPaging = repository.selectPaging("getBdcLimitTableConfigByPage", map, pageable);
        return dataPaging;
    }
}
