package com.ruoyi.web.controller.Ytj;

import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.WebSocketServer;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.HyDictionary;
import com.ruoyi.system.domain.QyCzrxx;
import com.ruoyi.system.domain.QyInfo;
import com.ruoyi.system.domain.QyPerson;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

import static com.ruoyi.common.utils.ImgUtils.Base64ToImage;


@Controller
@RequestMapping("/Ytj/qygsdz")
public class QygsglController extends BaseController {

    private String prefix = "Ytj/qygsdz";

    @Autowired
    private IQyPersonService qyPersonService;
    @Autowired
    private IYtjService ytjService;
    @Autowired
    private IQyInfoService qyInfoService;
    @Autowired
    private IQyCzrxxService qyCzrxxService;


    /**
     * 打开功能列表
     *
     * @return 页面
     */
    @GetMapping()
    public String index(ModelMap modelMap) {
        modelMap.put("city",Global.getCityName());
        return "Ytj/qyIndex";
    }

    /**
     * 打开刷身份证页面
     *
     * @return 页面
     */
    @GetMapping("/read/{type}")
    public String read(@PathVariable("type") String type,Model model) {
        model.addAttribute("city", Global.getCityName());
        model.addAttribute("type",type);
        return prefix + "/RCard";
    }

    /**
     * 读取采集信息
     *
     * @return
     */
    @GetMapping("/caiji/{type}")
    public String caiji(@PathVariable("type") String type ,Model model) {
        model.addAttribute("city", Global.getCityName());
        model.addAttribute("rzdbsocre", Global.getConfig("ruoyi.rzdbsocre"));
        String Bsid = UUID.randomUUID().toString();
        model.addAttribute("Bsid", Bsid);
        model.addAttribute("type", type);
        return prefix + "/Index";
    }
    /**
     * 提交身份证信息
     * @param qyPerson
     * @return
     */
    @PostMapping("/SubmitCard")
    @ResponseBody
    public AjaxResult saveCard(QyPerson qyPerson, @RequestParam("IsHere") String ishere) {

        qyPerson.setAddtime(new Date());
        int result=0;
        String pzPath= "/QySqImg/"+ DateUtils.datePaths()+"/" +UUID.randomUUID().toString().replaceAll("-","").toLowerCase()+".jpg";
        String qmPath= "/QySqImg/"+ DateUtils.datePaths()+"/" +UUID.randomUUID().toString().replaceAll("-","").toLowerCase()+".jpg";
        String txPath= "/QySqImg/"+ DateUtils.datePaths()+"/" +UUID.randomUUID().toString().replaceAll("-","").toLowerCase()+".jpg";
        if(Base64ToImage(qyPerson.getPaiphoto(),Global.getProfile()+pzPath)){
            qyPerson.setPaiphoto("/profile"+pzPath);
        }
        if(Base64ToImage(qyPerson.getRenqianming(),Global.getProfile()+qmPath)){
            qyPerson.setRenqianming("/profile"+qmPath);
        }
        if(Base64ToImage(qyPerson.getRenphoto(),Global.getProfile()+txPath)){
            qyPerson.setRenphoto("/profile"+txPath);
        }

        if(ishere.equals("0")) {
            result = qyPersonService.insertQyPerson(qyPerson);
        }else{
            result=qyPersonService.updateWtr(qyPerson);
        }
        if (result == 1) {
            return AjaxResult.success("保存成功");
        }
        return AjaxResult.warn("保存失败,请重试");
    }

    /**
     * 修改委托人信息
     * @param qyPerson
     * @return
     */
    @PostMapping("/updateCard")
    @ResponseBody
    public AjaxResult updateCard(QyPerson qyPerson) {

        int result = qyPersonService.updateWtr(qyPerson);
        if (result == 1) {
            return AjaxResult.success("保存成功");
        }
        return AjaxResult.warn("保存失败,请重试");
    }
    /**
     * 添加企业人员
     * @param
     * @return
     */
    @PostMapping("/addPerson")
    @ResponseBody
    public AjaxResult addPerson(String Bsid,String CjCardNo,String CjName,String CjPhone,String CjType) {

        QyPerson qyPerson=new QyPerson();
        qyPerson.setBsid(Bsid);
        qyPerson.setRencardno(CjCardNo);
        qyPerson.setRenname(CjName);
        qyPerson.setRenmoblie(CjPhone);
        qyPerson.setRentype(CjType);
        qyPerson.setRzqx("0");
        if(CjType.equals("法定代表人")){
            qyPerson.setCsfs("委派");
        }else if(CjType.equals("董事")){
            qyPerson.setCsfs("委派");
        }else if(CjType.equals("监事")){
            qyPerson.setCsfs("委派");
        }else if(CjType.equals("经理")){
            qyPerson.setCsfs("聘任");
        }
        int result = qyPersonService.insertQyPerson(qyPerson);
        List<QyPerson> qq=qyPersonService.selectQyPersonList(qyPerson);
        if (result == 1) {
            String czrurl= "http://api.sms.cn/sms/";
            String parme="";
            try{
                parme="ac=send&uid=qxspj&pwd=8d18d2eb316841db0998eeb67362ba4c&mobile="+CjPhone
                        + "&content=" + CjName+"您好！请您通过："+Global.getConfig("ruoyi.appAddress")+
                        "下载“视频认证”安卓App,使用您的身份证号，密码为身份证后六位，登录并完成认证。【"+Global.getCityName()+"行政审批局】";
                String czrresult= HttpUtils.sendGet(czrurl,parme);
                System.err.println(czrresult);
            }catch (Exception e) {
                e.printStackTrace();
            }
            return AjaxResult.success("保存成功",qq.get(0).getId());
        }
        return AjaxResult.warn("保存失败,请重试");
    }
    /**
     * 添加股东
     * @param
     * @return
     */
    @PostMapping("/addCzr")
    @ResponseBody
    public AjaxResult addCzr(String Bsid,String CjCardNo,String CjName,String CjPhone,String CjMoney,Date CjDate) {


        QyCzrxx qyCzrxx=new QyCzrxx();
        qyCzrxx.setBsid(Bsid);
        qyCzrxx.setCzrcardno(CjCardNo);
        qyCzrxx.setCzrname(CjName);
        qyCzrxx.setCzrphone(CjPhone);
        qyCzrxx.setCzrzj(CjMoney);
        qyCzrxx.setCzfs("货币");
        qyCzrxx.setRenjiaoqxtime(CjDate);
        qyCzrxx.setShijiaoqxtime(CjDate);
        qyCzrxx.setRzQx("0");
        qyCzrxx.setCzrtype("股东（出资人）");
        int result = qyCzrxxService.insertQyCzrxx(qyCzrxx);
        List<QyCzrxx> qq=qyCzrxxService.selectQyCzrxxList(qyCzrxx);
        if (result == 1) {
            String czrurl= "http://api.sms.cn/sms/";
            String parme="";
            try{
                parme="ac=send&uid=qxspj&pwd=8d18d2eb316841db0998eeb67362ba4c&mobile="+CjPhone
                        + "&content=" + CjName+"您好！请您通过："+Global.getConfig("ruoyi.appAddress")+
                        "下载“视频认证”安卓App,使用您的身份证号，密码为身份证后六位，登录并完成认证。【"+Global.getCityName()+"行政审批局】";
                String czrresult= HttpUtils.sendGet(czrurl,parme);
                System.err.println(czrresult);
            }catch (Exception e) {
                e.printStackTrace();
            }
            return AjaxResult.success("保存成功",qq.get(0).getId());
        }
        return AjaxResult.warn("保存失败,请重试");
    }

    /**
     * 身份证正反信息页面
     *
     * @return
     */
    @GetMapping("/GetCailiao")
    @ResponseBody
    public List<Map> GetCailiao(@RequestParam("hyid") String hyid, Model model) {

        List<Map> resul = qyPersonService.GetCailiao(hyid);
        if (resul.size() > 0) {
            return resul;
        }
        return null;
    }
    /**
     * 提交正反面信息
     *
     * @return
     */
    @PostMapping("/SendCailiao_Wtr")
    @ResponseBody
    public AjaxResult SendCailiao_Wtr(HttpServletRequest request) {
        String bsid = request.getParameter("bsid");
        String clname = request.getParameter("clname");
        String clindex = request.getParameter("clindex");
        String clsrc = request.getParameter("clsrc");
        String imgPath= "/QySqImg/"+ DateUtils.datePaths()+"/" +UUID.randomUUID().toString().replaceAll("-","").toLowerCase()+".jpg";
        if(Base64ToImage(clsrc,Global.getProfile()+imgPath)){
            clsrc="/profile"+imgPath;
        }
        QyPerson qyPerson=new QyPerson();
        qyPerson.setBsid(bsid);
        //qyPerson.setCzrsfz(clindex);
        int result;
        if (clindex.equals("1")) {
            qyPerson.setCzrsfz(clsrc);
            result=qyPersonService.updateWtr(qyPerson);
        }else if(clindex.equals("2")){
            qyPerson.setCzrsfz1(clsrc);
            result=qyPersonService.updateWtr(qyPerson);
        }else {
             result = -1;
        }
        System.err.println("res:"+result);
        if (result> 0) {
            return AjaxResult.success("保存成功",0);
        }
        return AjaxResult.warn("保存错误,请勿多拍!");
    }
    /**
     * 提交正反面信息
     *
     * @return
     */
    @PostMapping("/DelCailiao_Wtr")
    @ResponseBody
    public AjaxResult DelCailiao_Wtr(@RequestParam("bsid")String bsid,@RequestParam("clname") String clname,@RequestParam("clindex")String clindex) {

        return null;
    }

    /**
     * 返回登记信息界面
     * @param
     * @param bsid
     * @return
     */
    @GetMapping("/Jbxx")
    public String jbxx(@RequestParam("BSID")String bsid,@RequestParam("type")String type,Model model) {
        model.addAttribute("city", Global.getCityName());
        model.addAttribute("type", type);
        model.addAttribute("rzdbsocre", Global.getConfig("ruoyi.rzdbsocre"));
        return prefix+"/Jbxx";

    }
    /**
     * 返回登记信息界面
     * @param
     * @param bsid
     * @return
     */
//    @GetMapping("/GetUserCard")
//    public String getUserCard(@RequestParam("BSID")String bsid ,Model model) {
//
//        qyInfoService.selectQyInfoByBsId(bsid);
//
//        return prefix+"/Jbxx";
//
//    }

    /**
     * 查询行政区划
     * @return
     */
    @GetMapping(value="/GetQh")
    @ResponseBody
    public List<Map> QhList() {
        List<Map> qh = ytjService.GetQh();
        return qh;
    }

    /**
     * 根据pid查找区划
     * @param pid
     * @return
     * @throws UnsupportedEncodingException
     */
    @GetMapping(value="/GetQu")
    @ResponseBody
    public List<Map> GetQu(String pid) throws UnsupportedEncodingException {
        List<Map> map = ytjService.GetQu(pid);
        return map;
    }

    /**
     * 查找行业分类
     * @return
     * @throws UnsupportedEncodingException
     */
    @GetMapping(value="/GetHy")
    @ResponseBody
    public List<Map> GetHy() throws UnsupportedEncodingException {
        List<Map> map = ytjService.GetHy();
        return map;
    }

    /**
     * 查找行业分类子级
     * @param pid
     * @return
     * @throws UnsupportedEncodingException
     */
    @GetMapping(value="/GetChildHy")
    @ResponseBody
    public List<HyDictionary> GetChildHy(@RequestParam("pid") String pid) throws UnsupportedEncodingException {
        System.err.println(pid);
        List<HyDictionary> map = ytjService.GetChildHy(pid);
        return map;
    }

    /**
     * 提交企业信息
     *
     */
    @PostMapping("/SubmitForm")
    @ResponseBody
    public AjaxResult submitFrom(HttpServletRequest request){

        int result=qyInfoService.submitFrom(request);
        return AjaxResult.success(result);
    }

    /**
     * 返回登记信息界面
     * @param
     * @param bsid
     * @return
     */
    @GetMapping("/Ryxinxi")
    public String Ryxinxi(@RequestParam("bsid")String bsid,@RequestParam("qytype")String qytype,Model model) {
        model.addAttribute("city", Global.getCityName());
        return prefix+"/Ryxinxi";
    }
    /**
     * 提交企业信息
     *
     */
    @GetMapping("/getWtrxinxi")
    @ResponseBody
    public AjaxResult getWtrxinxi(@RequestParam("bsid") String bsid , @RequestParam("sjs")String sjs,Model model){
        List<QyPerson> result=qyPersonService.selectQyPersonBybsid(bsid);
        QyCzrxx czr=new QyCzrxx();
        czr.setBsid(bsid);
        List<QyCzrxx> czrx=qyCzrxxService.selectQyCzrxxList(czr);
        Map map=new HashMap();
        map.put("wtr",result);
        map.put("czr",czrx);
        return AjaxResult.success("查到委托人信息",map);
    }

    /**
     * 读取身份证人员信息
     *
     * @return
     */
    @GetMapping("/shuaCard")
    public String shuaCard(@RequestParam("bsid") String bsid,@RequestParam("rytype") String rytype,@RequestParam("qytype") String qytype, Model model) {
        model.addAttribute("city", Global.getCityName());
        return prefix + "/shuaCard";
    }

    /**
     * 人员信息录取页面
     *
     * @return
     */
    @GetMapping("/ryPaizhao")
    public String ryPaizhao(@RequestParam("bsid") String bsid,@RequestParam("rytype") String rytype,Model model) {
        model.addAttribute("city", Global.getCityName());
        model.addAttribute("rzdbsocre", Global.getConfig("ruoyi.rzdbsocre"));
        return prefix + "/ryPaizhao";
    }
    /**
     * 人员信息录取表单提交
     *
     * @return
     * */
    @PostMapping("/submitRy")
    @ResponseBody
    public AjaxResult ryPaizhao(QyPerson qyPerson) {

        if(qyPerson.getRentype().equals("法定代表人")){
            QyInfo info= new QyInfo();
            qyPerson.setIsfr("1");
            qyPerson.setCsfs("委派");
            info.setBsid(qyPerson.getBsid());
            info.setFrname(qyPerson.getRenname());
            qyInfoService.submitInfo(info);
        }
        if(qyPerson.getRentype().equals("监事")){
            qyPerson.setCsfs("委派");
        }else if(qyPerson.getRentype().equals("经理")){
            qyPerson.setCsfs("聘任");
        }else if(qyPerson.getRentype().equals("董事")){
            qyPerson.setCsfs("委派");
        }
        //自拍照
        String pzPath= "/QySqImg/"+ DateUtils.datePaths()+"/" +UUID.randomUUID().toString().replaceAll("-","").toLowerCase()+".jpg";
        //签名
        String qmPath= "/QySqImg/"+ DateUtils.datePaths()+"/" +UUID.randomUUID().toString().replaceAll("-","").toLowerCase()+".jpg";
        //身份证头像
        String txPath= "/QySqImg/"+ DateUtils.datePaths()+"/" +UUID.randomUUID().toString().replaceAll("-","").toLowerCase()+".jpg";
         //身份证0
        String czrsfz= "/QySqImg/"+ DateUtils.datePaths()+"/" +UUID.randomUUID().toString().replaceAll("-","").toLowerCase()+".jpg";
         //身份证1
        String czrsfz1= "/QySqImg/"+ DateUtils.datePaths()+"/" +UUID.randomUUID().toString().replaceAll("-","").toLowerCase()+".jpg";
        if(Base64ToImage(qyPerson.getPaiphoto(),Global.getProfile()+pzPath)){
            qyPerson.setPaiphoto("/profile"+pzPath);
        }
        if(Base64ToImage(qyPerson.getRenqianming(),Global.getProfile()+qmPath)){
            qyPerson.setRenqianming("/profile"+qmPath);
        }
        if(Base64ToImage(qyPerson.getRenphoto(),Global.getProfile()+txPath)){
            qyPerson.setRenphoto("/profile"+txPath);
        }
        if(Base64ToImage(qyPerson.getCzrsfz1(),Global.getProfile()+czrsfz1)){
            qyPerson.setCzrsfz1("/profile"+czrsfz1);
        }
        if(Base64ToImage(qyPerson.getCzrsfz(),Global.getProfile()+czrsfz)){
            qyPerson.setCzrsfz("/profile"+czrsfz);
        }
        int i = qyPersonService.insertQyPerson(qyPerson);
        if (i == 1) {
            return AjaxResult.success("保存成功");
        }
        return AjaxResult.warn("信息保存失败");
    }
    /**
     * 人员信息录取表单提交
     *
     * @return
     * */
    @PostMapping("/submitCzr")
    @ResponseBody
    public AjaxResult ryPaizhao(HttpServletRequest request) {


        int i = qyCzrxxService.insertQyCzr(request);
        if (i == 1) {
            return AjaxResult.success("出资人信息保存成功");
        }
        return AjaxResult.warn("出资人信息保存失败");
    }
    /**
     *
     * @param bsid
     * @return
     */
    @GetMapping("/getQrtjxinxi")
    @ResponseBody
    public AjaxResult getQrtjxinxi(@RequestParam("bsid") String bsid , @RequestParam("sjs")String sjs,Model model) {

        QyInfo result=qyInfoService.selectQyInfoByBsId(bsid);
        if(result==null){
            return AjaxResult.warn("不存在的企业信息");
        }
        return AjaxResult.success("企业信息",result);
    }

    /**
     * 人员信息录取表单提交
     *
     * @return
     * */
    @PostMapping("/SubmitTj")
    @ResponseBody
    public AjaxResult SubmitTj(@RequestParam("bsid")String bsid) {

        Date carteTime=new Date();
        QyInfo info= qyInfoService.selectQyInfoByBsId(bsid);
        info.setIsprintF("0");
        info.setIsprintZ("0");
        info.setFlg("0");
        info.setCreatedate(carteTime);
        info.setLqdate(carteTime);
        int i= qyInfoService.submitInfo(info);
        if (i == 1) {
                try {
                    WebSocketServer.sendInfo("企业独资："+ info.getFrname() +"的申请消息!请及时查办","0");
                        //flg代表着企业审核状态
                        int flg=0;
                        qyInfoService.sendMessage(info.getFrname(),info.getQylxdh(),info.getQyname(),"",flg);
                } catch (IOException e) {
                    e.printStackTrace();
                    System.err.println(e);
                }
            return AjaxResult.success("出资人信息保存成功");
        }
        return AjaxResult.warn("出资人信息保存失败");
    }
/**
     * 采集信息删除
     *
     * @return
     * */
    @PostMapping("/DelRY")
    @ResponseBody
    public int caijiDel(@RequestParam("bsid")String bsid,@RequestParam("ryid")Long ryid, @RequestParam("type") int type) {

        //type 0 代表出资人，1代表人员表
       if(type==0){
           return qyCzrxxService.deleteQyCzrxxById(ryid);
       }else if(type==1){
           return qyPersonService.deleteQyPersonById(ryid);
       }else {
           return -1;
       }
    }

    /**
     *  返回成功页面
     * @return
     */
    @GetMapping("/sl6")
    public String getQrtjxinxi(Model model) {
        model.addAttribute("city", Global.getCityName());
        return prefix+"/sl6";
    }
    /**
     * 遍历已经录入的人员信息
     * @param bsid
     * @return
     */
    @GetMapping("/getperson")
    @ResponseBody
    public AjaxResult getperson(@RequestParam("bsid")String bsid){

        List<QyPerson> qyPeople=qyPersonService.selectQyPersonBybsids(bsid);
        return AjaxResult.success("查找成功:", qyPeople);
    }

    /**
     * 快捷选择人员
     * @param id
     * @return
     */
    @GetMapping("/setperson")
    @ResponseBody
    public AjaxResult setperson( @RequestParam("id")Long id,@RequestParam("typeid") Integer typeid){

        QyPerson qyPeople=qyPersonService.selectQyPersonById(id);

        if (typeid == 0) {
            return  AjaxResult.warn("错误的选择");
        }

        if(typeid==1){
            qyPeople.setRentype("法定代表人");
            qyPeople.setIsfr("1");
            qyPeople.setCsfs("委派");
            QyInfo info= new QyInfo();
            info.setBsid(qyPeople.getBsid());
            info.setFrname(qyPeople.getRenname());
            qyInfoService.submitInfo(info);
        }else if(typeid==2){
            qyPeople.setRentype("董事");
            qyPeople.setCsfs("委派");
        }else if(typeid==3){
            qyPeople.setRentype("监事");
            qyPeople.setCsfs("委派");
        }else if(typeid==4){
            qyPeople.setRentype("经理");
            qyPeople.setCsfs("聘任");
        }else if(typeid==5){
            qyPeople.setRentype("财务负责人");
        }else if(typeid==6){
            qyPeople.setRentype("联络员");
        }
        qyPeople.setId(null);
        if("0".equals(qyPeople.getRzqx())){
            qyPeople.setRzqx("0");
        }
        qyPersonService.insertQyPerson(qyPeople);
        return AjaxResult.success("查找成功:", qyPeople);
    }

    /**
     * 获取到 保存的信息
     * @param card
     * @return
     */
    @GetMapping("/qyxinxi")
    @ResponseBody
    public AjaxResult qyxinxi (@RequestParam("card") String card){
        List<QyInfo> infos= qyInfoService.selectQyInfoByCard(card);
        if(infos.size()>0) {
            for (QyInfo in : infos) {
                if(in.getFlg()==null) {
                    if(in.getQylx().equals("有限责任公司（自然人独资）")||in.getQylx().equals("个人独资企业")) {
                        return AjaxResult.success("未进行完的信息", in);
                    }
                }

            }
        }
        return AjaxResult.warn("暂无信息");
    }



}
