package com.ruoyi.web.controller.Ytjback;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MapUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.GtgsBg;
import com.ruoyi.system.domain.GtgsZx;
import com.ruoyi.system.domain.GtgsywPrintList;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.GtgsywPrintListService;
import com.ruoyi.system.service.IGtgsBgService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.tool.FtlToWordUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 个体工商变更Controller
 *
 * @author ruoyi
 * @date 2020-05-13
 */
@Controller
@RequestMapping("/system/bg")
public class GtgsBgBackController extends BaseController {
    private String prefix = "system/bg";

    @Autowired
    private IGtgsBgService gtgsBgService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private GtgsywPrintListService gtgsywPrintListService;

    //    @RequiresPermissions("system:bg:view")
    @GetMapping("/index")
    public String bg(ModelMap modelMap) {
        modelMap.addAttribute("spflg", 0);
        return prefix + "/bg";
    }

    @GetMapping("/inreview")
    public String bg1(ModelMap modelMap) {
        modelMap.addAttribute("spflg", 1);
        return prefix + "/inreview";
    }

    @GetMapping("/pass")
    public String bg2(ModelMap modelMap) {
        modelMap.addAttribute("spflg", 2);
        return prefix + "/pass";
    }

    @GetMapping("/back")
    public String bg3(ModelMap modelMap) {
        modelMap.addAttribute("spflg", 3);
        return prefix + "/back";
    }

    /**
     * 查询个体工商变更列表
     */
    @RequiresPermissions("system:bg:list")
    @PostMapping("/list/{spflg}")
    @ResponseBody
    public TableDataInfo list(@PathVariable("spflg") String spflg, GtgsBg gtgsBg) {
        System.err.println("spflg:" + spflg);
        gtgsBg.setFlag(spflg);
        if (String.valueOf(1).equals(gtgsBg.getFlag()) && !ShiroUtils.getLoginName().equals("admin")) {
            gtgsBg.setArchiveBy(ShiroUtils.getSysUser().getUserName());
        }
        startPage();
        List<GtgsBg> list = gtgsBgService.selectGtgsBgList(gtgsBg);
        return getDataTable(list);

    }

    /**
     * 导出个体工商变更列表
     */
    @RequiresPermissions("system:bg:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(GtgsBg gtgsBg) {
        List<GtgsBg> list = gtgsBgService.selectGtgsBgList(gtgsBg);
        ExcelUtil<GtgsBg> util = new ExcelUtil<GtgsBg>(GtgsBg.class);
        return util.exportExcel(list, "bg");
    }

    /**
     * 新增个体工商变更
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存个体工商变更
     */

    @RequiresPermissions("system:bg:add")
    @Log(title = "个体工商变更", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(GtgsBg gtgsBg) {
        return toAjax(gtgsBgService.insertGtgsBg(gtgsBg));
    }

    /**
     * 修改个体工商变更
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        GtgsBg gtgsBg = gtgsBgService.selectGtgsBgById(id);
        mmap.put("gtgsBg", gtgsBg);
        return prefix + "/edit";
    }

    /**
     * 修改保存个体工商变更
     */
//    @RequiresPermissions("system:bg:edit")
//    @Log(title = "个体工商变更", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(GtgsBg gtgsBg) {
        return toAjax(gtgsBgService.updateGtgsBg(gtgsBg));
    }


    /**
     * 删除个体工商变更
     */
     @RequiresPermissions("system:bg:remove")
      @Log(title = "个体工商变更", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(gtgsBgService.deleteGtgsBgByIds(ids));
    }


    /**
     * 审核变更前台列表
     */
    //  @RequiresPermissions("system:bg:edit")
//    @GetMapping("/check/{id}")
//    public String checkBG(@PathVariable("id") String id, ModelMap modelMap) {
//
//        GtgsBg gtgsBg = gtgsBgService.selectGtgsBgById(id);
//       gtgsBg.setCheckTime(DateUtils.getNowDate());
//        gtgsBg.setFlag("1");
//        gtgsBg.setArchiveBy(ShiroUtils.getSysUser().getLoginName());
//        gtgsBg.setFlag(String.valueOf(1));
//        modelMap.addAttribute("gtgsBg", gtgsBg);
//        ShiroUtils.getSysUser().getUserName();
//        gtgsBgService.updateGtgsBg(gtgsBg);
//        modelMap.put("gtgsBg", gtgsBg);
//        return prefix + "/check";
    //  }
    @RequiresPermissions("system:bg:edit")
    @GetMapping("/check/{id}")
    public String checkBG(@PathVariable("id") String id, ModelMap modelMap) {
        Calendar calendar = Calendar.getInstance();
        GtgsBg gtgsBg = gtgsBgService.selectGtgsBgById(id);
        if (gtgsBg.getArchiveBy() == null || gtgsBg.getArchiveBy().isEmpty() ||gtgsBg.getArchiveBy().equals(ShiroUtils.getSysUser().getUserName())||ShiroUtils.getSysUser().isAdmin()) {
            gtgsBg.setCheckTime(DateUtils.getNowDate());
            if (gtgsBg.getArchiveBy() == null || gtgsBg.getArchiveBy().isEmpty() ) {
                gtgsBg.setArchiveBy(ShiroUtils.getSysUser().getUserName());
            }
            gtgsBg.setFlag(String.valueOf(1));
            gtgsBgService.changeGtgsFlagTg(gtgsBg);
            modelMap.addAttribute("gtgsBg", gtgsBg);
            modelMap.addAttribute("year", calendar.get(Calendar.YEAR));
            return prefix + "/check";
        } else {
            throw new BusinessException("服务器出现错误或这个申请已被他人处理，请刷新后重试！");
        }
    }
    @RequiresPermissions("system:bg:edit")
    @GetMapping("/view/{id}")
    public String viewBG(@PathVariable("id") String id, ModelMap modelMap) {
        GtgsBg gtgsBg = gtgsBgService.selectGtgsBgById(id);
        gtgsBg.setArchiveBy(gtgsBg.getArchiveBy());
        modelMap.addAttribute("gtgsBg", gtgsBg);
        return prefix + "/view";
    }
    @RequiresPermissions("system:bg:edit")
    @PostMapping("/update")
    @ResponseBody
    public AjaxResult update(GtgsBg gtgsBg) {
        GtgsBg gtgsBg1 = gtgsBgService.selectGtgsBgById(gtgsBg.getId());

        if (Integer.valueOf(gtgsBg1.getFlag()) > 1) {

            return AjaxResult.warn("此申请已被处理完成！");
        } else if (!gtgsBg1.getArchiveBy().equals(ShiroUtils.getSysUser().getUserName())) {
            return AjaxResult.warn("此申请已归到他人审核！您没有权限处理。");
        }
        gtgsBg.setArchiveTime(DateUtils.getNowDate());

        //审核通过后添加到打印表中
        GtgsywPrintList gtgsywPrintList = new GtgsywPrintList();
        gtgsywPrintList.setBsid(gtgsBg1.getId());
        gtgsywPrintList.setType("变更");
        gtgsywPrintList.setJingyingcard(gtgsBg1.getOperatorIdCard());
        gtgsywPrintList.setXinyongcode(gtgsBg1.getUniformSocialCreditCode());
        gtgsywPrintList.setAppno(gtgsBg1.getRegistrationNumber());


        //个体名称
        if (gtgsBg1.getAlterationCompanyName() != null && gtgsBg1.getAlterationCompanyName().equals("on")) {
            gtgsywPrintList.setZwzh(gtgsBg1.getNewCompanyName());
        } else {
            gtgsywPrintList.setZwzh(gtgsBg1.getCompanyName());
        }
        //经营范围
        if (gtgsBg1.getAlterationBusinessScope() != null && gtgsBg1.getAlterationBusinessScope().equals("on")) {
            gtgsywPrintList.setJingyingfanwei(gtgsBg1.getNewBusinessScope());
        } else {
            gtgsywPrintList.setJingyingfanwei(gtgsBg1.getBusinessScope());
        }
        //经营场所
        if (gtgsBg1.getAlterationPremisesAddr() != null && gtgsBg1.getAlterationPremisesAddr().equals("on")) {
            gtgsywPrintList.setJingyingchangsuo(gtgsBg1.getNewPremisesAddr());
        } else {
            gtgsywPrintList.setJingyingchangsuo(gtgsBg1.getPremisesAddr());
        }
        //组成形式
        gtgsywPrintList.setZuchengxingshi(gtgsBg1.getOrganizationType());
        //从业人数
        gtgsywPrintList.setCongyerenshu(Integer.valueOf(gtgsBg1.getEmployee()));
        //经营人
        gtgsywPrintList.setJingyingren(gtgsBg1.getOperatorName());
        //申请时间
        gtgsywPrintList.setShenqingdate(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", gtgsBg1.getCreateTime()));
        //申请来源
        gtgsywPrintList.setShenqinglaiyuan(gtgsBg1.getApplyForSource());
        //审核人
        gtgsywPrintList.setShenherenname(gtgsBg1.getArchiveBy());
        //审核日期
        gtgsywPrintList.setShenhedate(gtgsBg1.getArchiveTime());
        //更新日期
        gtgsywPrintList.setUpdateTime(gtgsBg1.getArchiveTime());
        //类型
        gtgsywPrintList.setSczttype("个体工商户");
        //二维码
        gtgsywPrintList.setErweimabase64(gtgsBg1.getBusinessLicenseQrcode());
        //注册时间
        gtgsywPrintList.setZhucetime(gtgsBg1.getRegisterTime());

        gtgsywPrintListService.insertSelective(gtgsywPrintList);
        return toAjax(gtgsBgService.changeGtgsFlagTg(gtgsBg));
    }


    /**
     * 下载档案
     */
//    @RequiresPermissions("system:bg:edit")
    @PostMapping("/download")
    @ResponseBody
    public AjaxResult download(String id, String type) {
        try {
            GtgsBg gtgsBg = gtgsBgService.selectGtgsBgById(id);
            gtgsBg.setOperatorSignature(gtgsBg.getOperatorSignature().replace("data:image/jpeg;base64,", ""));
            gtgsBg.setOperatorCardFore(gtgsBg.getOperatorCardFore().replace("data:image/jpeg;base64,", ""));
            gtgsBg.setOperatorCardBack(gtgsBg.getOperatorCardBack().replace("data:image/jpeg;base64,", ""));
            gtgsBg.setOperatorPhoto(gtgsBg.getOperatorPhoto().replace("data:image/jpeg;base64,", ""));
            if (gtgsBg.getBusinessLicenseProve() != null && !gtgsBg.getBusinessLicenseProve().trim().equals("")) {
                gtgsBg.setBusinessLicenseProve(gtgsBg.getBusinessLicenseProve().replace("data:image/jpeg;base64,", ""));
            }
            Map<String, Object> valueMap = MapUtils.getValueMap(gtgsBg);
            SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
            valueMap.put("createTimeStr", format.format(gtgsBg.getCreateTime()));
            valueMap.put("checkTimeStr", format.format(gtgsBg.getCheckTime()));
            valueMap.put("archiveTimeStr", format.format(gtgsBg.getArchiveTime()));
            valueMap.put("saveTimeStr", format.format(plusDay2(gtgsBg.getArchiveTime())));
            valueMap.put("cityName", Global.getCityName());
            FtlToWordUtils dh = new FtlToWordUtils();
            String docPath;
            String companyName = "";
            if ("on".equals(gtgsBg.getAlterationCompanyName()) && gtgsBg.getNewCompanyName() != null && !gtgsBg.getNewCompanyName().trim().equals("") && !gtgsBg.getNewCompanyName().isEmpty()) {
                companyName = gtgsBg.getNewCompanyName();
            } else {
                companyName = gtgsBg.getCompanyName();
            }
            companyName += UUID.randomUUID().toString().replaceAll("-", "");
            switch (type) {
                case "1":
                    //预先登记
                    docPath = dh.createDoc("gtgsbgchangename.ftl", companyName, valueMap);
                    break;
                default:
                    docPath = dh.createDoc("gtgsbgbase.ftl", companyName, valueMap);
            }
            return AjaxResult.success(docPath);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }

    }

    public Date plusDay2(Date date) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(date);
        ca.add(Calendar.MONTH, 6);
        ca.add(Calendar.DATE, 1);
        date = ca.getTime();
        return date;
    }
}
