/**
 * 请勿将俱乐部专享资源复制给其他人，保护知识产权即是保护我们所在的行业，进而保护我们自己的利益
 * 即便是公司的同事，也请尊重 JFinal 作者的努力与付出，不要复制给同事
 * <p>
 * 如果你尚未加入俱乐部，请立即删除该项目，或者现在加入俱乐部：http://jfinal.com/club
 * <p>
 * 俱乐部将提供 jfinal-club 项目文档与设计资源、专用 QQ 群，以及作者在俱乐部定期的分享与答疑，
 * 价值远比仅仅拥有 jfinal club 项目源代码要大得多
 * <p>
 * JFinal 俱乐部是五年以来首次寻求外部资源的尝试，以便于有资源创建更加
 * 高品质的产品与服务，为大家带来更大的价值，所以请大家多多支持，不要将
 * 首次的尝试扼杀在了摇篮之中
 */

package com.jfinal.club.my.newsfeed;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.club.common.controller.BaseController;
import com.jfinal.club.common.interceptor.FrontAuthInterceptor;
import com.jfinal.club.common.model.*;
import com.jfinal.club.common.upload.UploadService;
import com.jfinal.club.download.DownloadService;
import com.jfinal.club.login.LoginService;
import com.jfinal.club.my.favorite.FavoriteService;
import com.jfinal.club.my.safe.UserUpdateValidator;
import com.jfinal.club.util.Cons;
import com.jfinal.club.ws.DocWsService;
import com.jfinal.club.ws.DocWsValidator;
import com.jfinal.club.ws.WsInfoService;
import com.jfinal.club.ws.WsmanService;
import com.jfinal.core.ActionKey;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import sun.java2d.pipe.SpanIterator;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 个人信息
 */
@Log4j
@Before({FrontAuthInterceptor.class, UsersInfoIntreceptor.class})
public class UsersController extends BaseController {

    @Inject
    UsersService usersService;

    @Inject
    DownloadService downloadService;

    @Inject
    DocWsService docWsService;
    @Inject
    FavoriteService favoriteService;

    @Inject
    WsDownloadService wsDownloadService;

    @Inject
    WsInfoService wsInfoService;

    @Inject
    WsmanService wsmanService;

    @ActionKey("/my")
    public void mewsFeed( ) {
        setAttr("bs_set", true);
        setAttr("loginUsers", usersService.findUsersById(getloginUsersId( )));
        render("my_infor.html");
    }


    public void download( ) {
        Page< Download > downloadList = downloadService.getDownloadList(getloginUsersId( ), getPara("text"), getParaToInt("p", 1));
        setAttr("downloadList", downloadList);
        setAttr("my_down", true);
        render("download.html");
    }

    @Before(UserUpdateValidator.class)
    public void doUsers( ) {
        UploadFile file = getFile("users.tximg", Cons.TEMP);
        Users users = getModel(Users.class);
        if (file != null) {
            Ret ret1 = UploadService.uploadAvatar(getloginUsersId( ), file, Cons.USER_IMG);
            users.setTximg(ret1.getStr("img"));
        }
        //更新生日
        String birthday = users.getBirthday( );
        if (StringUtils.isNotBlank(birthday)) {
            String[] split = birthday.split("-");
            users.setYear(split[0]);
            users.setMonth(split[1]);
            users.setDay(split[2]);
        }
        boolean update = users.removeNullValueAttrs( ).update( );
        if (update) {
            renderJson(Ret.ok("msg", "更新成功"));
        } else {
            renderJson(Ret.fail("msg", "更新失败"));
        }
    }


    /**
     * @return
     * @Author Cc
     * @Description //TODO type  = 1 法律文档 2 法律百科 3 法律问答
     * @Date 2020/3/24
     * @Param
     **/
    public void myCollect( ) {
        Integer type = getParaToInt("type", 1);
        Page< Favorite > page = favoriteService.getOneByUserIdType(getInt("p", 1), Cons.FRONT_PAGE_SIZE, getloginUsersId( ), type);
        setAttr("type", type);
        setAttr("my_coll", true);
        setAttr("listPage", page);
        render("my_collect.html");
    }


    /**
     * @return void
     * @Author Cc
     * @Description //TODO 我的文书
     * @Date 2020/3/24
     * @Param []
     **/
    public void myWs( ) {
        Page< Wsinfo > p = wsInfoService.myws(getloginUsersId( ), getInt("p", 1), Cons.FRONT_PAGE_SIZE);
        setAttr("WsinfoPage", p);
        setAttr("my_ws", true);
        render("my_ws.html");
    }

    public void myws_pass( ) {
        Page< Docws > p = docWsService.getDocwsByUsersId(getloginUsersId( ), getParaToInt("p", 1), 1);
        setAttr("docwsPage", p);
        setAttr("my_ws", true);
        render("my_ws_pass.html");
    }


    /**
     * @return void
     * @Author Cc
     * @Description //TODO 删除文书
     * @Date 2020/3/24
     * @Param []
     **/
    @Clear
    public void delWs( ) {
        Integer wsid = getInt("id");
        //首先删除掉子类   然后删除自己
        wsmanService.deletByWsid(wsid);
        renderJson(Ret.ok("msg","删除成功!"));

    }

    /**
     * @return void
     * @Author Cc
     * @Description //TODO 文书编辑
     * @Date 2020/3/24
     * @Param []
     **/
    public void wsEdit( ) {
        Integer wsid = getParaToInt("id");

        List< Wsman > ygList = wsmanService.listByWsIdYgbg(wsid, Cons.ONE);
        List< Wsman > bgList = wsmanService.listByWsIdYgbg(wsid, Cons.TWO);
        Wsinfo wsinfo = wsInfoService.getById(wsid);
        List< Nation > nations = docWsService.saveNation( );

        List< String > list = null;
        if (StringUtils.isNotBlank(wsinfo.getImg( ))) {
            list = Arrays.asList(wsinfo.getImg( ).split(","));
        }
        setAttr("imgList", list);
        setAttr("nations", nations);
        setAttr("ygList", ygList);
        setAttr("bgList", bgList);
        setAttr("wsinfo", wsinfo);
        render("ws_edit.html");
    }

    /**
     * 文书下载
     */
    @Clear
    public void wsDownload( )  {
        try {
            Integer wsId = getInt("id");
            String wsFile = wsDownloadService.createWord(wsId);
            if (wsFile != null) {
                renderFile(new File(PathKit.getWebRootPath( ) + wsFile));
            } else {
                redirect("/my");
            }
        } catch (IOException e) {
            redirect("/my");
        }
    }

    /**
     * @return void
     * @Author Cc
     * @Description //TODO 文书修改
     * @Date 2020/3/24
     * @Param []
     **/
    @Before({DocWsValidator.class})
    public void wsUpdat( ) {
        Integer wsid = getInt("wsinfo.id");
        //文书信息
        HttpServletRequest request = getRequest( );
        //更新文书信息
        {
            Wsinfo wsinfo = wsInfoService.getById(wsid);
            wsinfo.setWsType(get("wsinfo.wsType"));
            wsinfo.setWsRequest(get("wsinfo.wsRequest"));
            wsinfo.setWsReason(get("wsinfo.wsReason"));
            wsinfo.setMaterialName(get("wsinfo.materialName"));
            wsinfo.setEvidence(get("wsinfo.evidence"));
            wsinfo.setLawyer(get("wsinfo.lawyer"));
            wsinfo.setMoney(Double.valueOf(get("wsinfo.money")));
            String subImg;
            String img = Arrays.toString(getRequest( ).getParameterValues("img"));
            if (StringUtils.isNotBlank(img) && !img.equals("null") && !img.equals("[]")) {
                subImg = img.substring(1, img.lastIndexOf("]"));
                wsinfo.setImg(subImg.replace(" ", ""));
            }
            wsinfo.removeNullValueAttrs( ).update( );
        }
        //更新原告人信息
        {
            List< String > ygid = Arrays.asList(request.getParameterValues("yg.id"));
            List< String > ygmtype = Arrays.asList(request.getParameterValues("yg.mtype"));
            List< String > ygname = Arrays.asList(request.getParameterValues("yg.name"));
            List< String > yggender = Arrays.asList(request.getParameterValues("yg.gender"));
            List< String > ygbirthday = Arrays.asList(request.getParameterValues("yg.birthday"));
            List< String > ygnation = Arrays.asList(request.getParameterValues("yg.nation"));
            List< String > yghujiAddress = Arrays.asList(request.getParameterValues("yg.hujiAddress"));
            List< String > ygphone = Arrays.asList(request.getParameterValues("yg.phone"));
            List< String > ygidType = Arrays.asList(request.getParameterValues("yg.idType"));
            List< String > ygidNumber = Arrays.asList(request.getParameterValues("yg.idNumber"));


            List< String > company = Arrays.asList(request.getParameterValues("yg.company"));
            List< String > legalPerson = Arrays.asList(request.getParameterValues("yg.legalPerson"));
            List< String > companyAddress = Arrays.asList(request.getParameterValues("yg.companyAddress"));
            List< String > creditCode = Arrays.asList(request.getParameterValues("yg.creditCode"));
            List< String > legalPhone = Arrays.asList(request.getParameterValues("yg.legalPhone"));

            List< Wsman > ygList = new ArrayList<>( );
            if (ygid != null && ygid.size( ) > 0) {
                for (int i = 0; i < ygid.size( ); i++) {
                    Wsman w = new Wsman( );
                    w.setId(Integer.valueOf(ygid.get(i)));
                    w.setMtype(ygmtype.get(i));
                    w.setName(ygname.get(i));
                    w.setGender(yggender.get(i));
                    w.setBirthday(ygbirthday.get(i));
                    w.setNation(ygnation.get(i));
                    w.setHujiAddress(yghujiAddress.get(i));
                    w.setPhone(ygphone.get(i));
                    w.setIdType(ygidType.get(i));
                    w.setIdNumber(ygidNumber.get(i));

                    w.setCompany(company.get(i));
                    w.setLegalPerson(legalPerson.get(i));
                    w.setCompanyAddress(companyAddress.get(i));
                    w.setCreditCode(creditCode.get(i));
                    w.setLegalPhone(legalPhone.get(i));
                    ygList.add(w);
                }
            }
            Db.batchUpdate(ygList, 200);
        }
        //更新被告信息
        {
            List< String > bgid = Arrays.asList(request.getParameterValues("bg.id"));
            List< String > bgmtype = Arrays.asList(request.getParameterValues("bg.mtype"));
            List< String > bgname = Arrays.asList(request.getParameterValues("bg.name"));
            List< String > bggender = Arrays.asList(request.getParameterValues("bg.gender"));
            List< String > bgbirthday = Arrays.asList(request.getParameterValues("bg.birthday"));
            List< String > bgnation = Arrays.asList(request.getParameterValues("bg.nation"));
            List< String > bghujiAddress = Arrays.asList(request.getParameterValues("bg.hujiAddress"));
            List< String > bgnowAddress = Arrays.asList(request.getParameterValues("bg.nowAddress"));
            List< String > bgphone = Arrays.asList(request.getParameterValues("bg.phone"));
            List< String > bgidType = Arrays.asList(request.getParameterValues("bg.idType"));
            List< String > bgidNumber = Arrays.asList(request.getParameterValues("bg.idNumber"));

            List< String > company = Arrays.asList(request.getParameterValues("bg.company"));
            List< String > legalPerson = Arrays.asList(request.getParameterValues("bg.legalPerson"));
            List< String > companyAddress = Arrays.asList(request.getParameterValues("bg.companyAddress"));
            List< String > creditCode = Arrays.asList(request.getParameterValues("bg.creditCode"));
            List< String > legalPhone = Arrays.asList(request.getParameterValues("bg.legalPhone"));
            List< Wsman > bgList = new ArrayList<>( );
            if (bgid != null && bgid.size( ) > 0) {
                for (int i = 0; i < bgid.size( ); i++) {
                    Wsman w = new Wsman( );
                    w.setId(Integer.valueOf(bgid.get(i)));
                    w.setMtype(bgmtype.get(i));
                    w.setName(bgname.get(i));
                    w.setGender(bggender.get(i));
                    w.setBirthday(bgbirthday.get(i));
                    w.setNation(bgnation.get(i));
                    w.setHujiAddress(bghujiAddress.get(i));
                    w.setNowAddress(bgnowAddress.get(i));
                    w.setPhone(bgphone.get(i));
                    w.setIdType(bgidType.get(i));
                    w.setIdNumber(bgidNumber.get(i));

                    w.setCompany(company.get(i));
                    w.setLegalPerson(legalPerson.get(i));
                    w.setCompanyAddress(companyAddress.get(i));
                    w.setCreditCode(creditCode.get(i));
                    w.setLegalPhone(legalPhone.get(i));
                    bgList.add(w);
                }
            }
            Db.batchUpdate(bgList, 200);
        }
        renderJson(Ret.ok( ));
    }


    //动态添加用
    public void wsUpdats( ) {
        wsUpdat();
    }

}
