package com.ruoyi.project.invoice.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.data.Texts;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.project.invoice.domain.TInvoiceContractor;
import com.ruoyi.project.invoice.domain.TInvoiceWorkcontent;
import com.ruoyi.project.invoice.service.ITInvoiceContractorService;
import com.ruoyi.project.invoice.service.ITInvoiceWorkcontentService;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.service.ISysDictTypeService;
import io.jsonwebtoken.lang.Assert;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.invoice.domain.TInvoiceBookingworkticket;
import com.ruoyi.project.invoice.service.ITInvoiceBookingworkticketService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 预约作业票台账Controller
 *
 * @author ruoyi
 * @date 2022-08-25
 */
@RestController
@RequestMapping("/invoice/bookingworkticket")
public class TInvoiceBookingworkticketController extends BaseController
{
    @Autowired
    private ITInvoiceBookingworkticketService tInvoiceBookingworkticketService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;
    /**
     * 查询预约作业票台账列表
     */
    @PreAuthorize("@ss.hasPermi('invoice:bookingworkticket:list')")
    @GetMapping("/list")
    public TableDataInfo list(TInvoiceBookingworkticket tInvoiceBookingworkticket)
    {
        startPage();
        List<TInvoiceWorkcontent>  newtInvoiceWorkcontentList =new ArrayList<>();
        List<TInvoiceBookingworkticket> bookingworkticketList = tInvoiceBookingworkticketService.selectTInvoiceBookingworkticketList(tInvoiceBookingworkticket);
        for(int i=0;i<bookingworkticketList.size();i++){
            //遍历每一条主表  找到所有的子表 根据每条子表 将主表也同步到每一条数据
            TInvoiceBookingworkticket bookingworkticket= bookingworkticketList.get(i);
           List<TInvoiceWorkcontent>  workcontentList = tInvoiceBookingworkticketService.selectTInvoiceWorkcontentBybookingticketId(bookingworkticket.getId());
           for (TInvoiceWorkcontent workcontent : workcontentList) {
                       workcontent.setBookingworkticket(bookingworkticket);
               newtInvoiceWorkcontentList.add(workcontent);
           }

        }
        return getDataTable(newtInvoiceWorkcontentList);
    }

    /**
     * 导出预约作业票台账列表
     */
    @PreAuthorize("@ss.hasPermi('invoice:bookingworkticket:export')")
    @Log(title = "预约作业票台账", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TInvoiceBookingworkticket tInvoiceBookingworkticket)
    {
        List<TInvoiceBookingworkticket> list = tInvoiceBookingworkticketService.selectTInvoiceBookingworkticketList(tInvoiceBookingworkticket);
        ExcelUtil<TInvoiceBookingworkticket> util = new ExcelUtil<TInvoiceBookingworkticket>(TInvoiceBookingworkticket.class);
        return util.exportExcel(list, "bookingworkticket");
    }

    /**
     * 获取预约作业票台账详细信息
     */
    @PreAuthorize("@ss.hasPermi('invoice:bookingworkticket:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
      TInvoiceBookingworkticket t=  tInvoiceBookingworkticketService.selectTInvoiceBookingworkticketById(id);
      List<TInvoiceWorkcontent>  list= tInvoiceBookingworkticketService.selectTInvoiceWorkcontentBybookingticketId(t.getId());
           t.settInvoiceWorkcontentList(list);
        return AjaxResult.success(t);
    }

    /**
     * 新增预约作业票台账
     */
    @PreAuthorize("@ss.hasPermi('invoice:bookingworkticket:add')")
    @Log(title = "预约作业票台账", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TInvoiceBookingworkticket tInvoiceBookingworkticket)
    {
       //先查当前登录的用户关联的承包商信息
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        TInvoiceContractor t= tInvoiceBookingworkticketService.selectTInvoiceContractorByName(loginUser.getUsername());
        tInvoiceBookingworkticket.setCreaterCode(getUserId());
     //   tInvoiceBookingworkticket.setContact(t.getContact());
     //   tInvoiceBookingworkticket.setPhonenumber(t.getPhonenumber());
        // 测试一下，先得到这个文件名 地址   在赋值插入 然后赋值 改文件名
        tInvoiceBookingworkticketService.insertTInvoiceBookingworkticket(tInvoiceBookingworkticket);
        try {
            String url=  PreView(tInvoiceBookingworkticket.getId());
            tInvoiceBookingworkticket.setFilename(url);
            tInvoiceBookingworkticketService.updateTInvoiceBookingworkticket(tInvoiceBookingworkticket);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Long didi=tInvoiceBookingworkticket.getId();
        List<TInvoiceWorkcontent>  w=tInvoiceBookingworkticket.gettInvoiceWorkcontentList();

        for(int i=0;i<w.size();i++){
             TInvoiceWorkcontent wt= w.get(i);
            wt.setBookingticketId(didi);
            tInvoiceBookingworkticketService.insertTInvoiceWorkcontent(wt);
        }

        return AjaxResult.success(didi);
    }

    /**
     * 修改预约作业票台账
     */
    @PreAuthorize("@ss.hasPermi('invoice:bookingworkticket:edit')")
    @Log(title = "预约作业票台账", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TInvoiceBookingworkticket tInvoiceBookingworkticket)
    {
        //这是修改时上传的 list ，先全部清空，在重新添加现有的
        List<Long>   ids =new ArrayList<>();
         List<TInvoiceWorkcontent>  tInvoiceWorkcontentList =tInvoiceBookingworkticket.gettInvoiceWorkcontentList();
      List<TInvoiceWorkcontent> oldtInvoiceWorkcontentList= tInvoiceBookingworkticketService.selectTInvoiceWorkcontentBybookingticketId(tInvoiceBookingworkticket.getId());
        for (TInvoiceWorkcontent workcontent : oldtInvoiceWorkcontentList) {
        ids.add((workcontent.getId()));
        }
        Long[] workcontentIds=ids.toArray(new Long[0]);
         tInvoiceBookingworkticketService.deleteTInvoiceWorkcontentByIds(workcontentIds);
        for (TInvoiceWorkcontent workcontent : tInvoiceWorkcontentList) {
            workcontent.setBookingticketId(tInvoiceBookingworkticket.getId());
           tInvoiceBookingworkticketService.insertTInvoiceWorkcontent(workcontent);
        }

        return toAjax(tInvoiceBookingworkticketService.updateTInvoiceBookingworkticket(tInvoiceBookingworkticket));
    }

    /**
     * 删除预约作业票台账
     */
    @PreAuthorize("@ss.hasPermi('invoice:bookingworkticket:remove')")
    @Log(title = "预约作业票台账", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tInvoiceBookingworkticketService.deleteTInvoiceBookingworkticketByIds(ids));
    }

    /**
     * 关联票号
     */
    @PreAuthorize("@ss.hasAnyRoles ('dbbz,admin')")
    @Log(title = "关联票号", businessType = BusinessType.OTHER)
    @DeleteMapping("/association")
    public AjaxResult association(@PathVariable Long[] ids)
    {
        return toAjax(tInvoiceBookingworkticketService.deleteTInvoiceBookingworkticketByIds(ids));
    }


    /**
     *
     * @param id   生成文件名
     * @return
     * @throws IOException
     */
    public String PreView(Long id) throws IOException {
        TInvoiceBookingworkticket tInvoiceBookingworkticket= tInvoiceBookingworkticketService.selectTInvoiceBookingworkticketById(id);
        String url = this.createBookingworkticketWord(tInvoiceBookingworkticket);
        return url;
    }

    /**
     * 生成word
     */
    public String createBookingworkticketWord(TInvoiceBookingworkticket invoiceBookingworkticket) throws IOException {
        //生成word
        //渲染文本
        Map<String, Object> params = getWordData(invoiceBookingworkticket);
        // 模板路径
        String templatePath = "static/word/invoice/book.docx";
        // 生成word的路径
        String fileDir = RuoYiConfig.getProfile() + "/"+ "ticketWord";
        // 生成word的文件
        String fileName = "A" + invoiceBookingworkticket.getContact() + ".docx";
        String wordPath = this.createWord(templatePath, fileDir, fileName, params);

        return wordPath;
    };


    /**
     * 获取word数据
     */
    public Map<String, Object> getWordData (TInvoiceBookingworkticket ticket){
        Map<String, Object> params = new HashMap<>();
        List<TInvoiceWorkcontent> tInvoiceWorkcontentList= tInvoiceBookingworkticketService.selectTInvoiceWorkcontentBybookingticketId(ticket.getId());
        //字典查询
        List<SysDictData> book_work_type = iSysDictTypeService.selectDictDataByType("book_work_type");
        List<SysDictData> book_work_unit = iSysDictTypeService.selectDictDataByType("book_work_unit");
        List<SysDictData> book_user_unit = iSysDictTypeService.selectDictDataByType("book_user_unit");
        List<SysDictData> book_risk_level = iSysDictTypeService.selectDictDataByType("book_risk_level");
        List<SysDictData> book_work_area = iSysDictTypeService.selectDictDataByType("book_work_area");
        List<SysDictData> book_user_mg = iSysDictTypeService.selectDictDataByType("book_user_mg");
       for(int i =0;i<tInvoiceWorkcontentList.size();i++){
           TInvoiceWorkcontent tInvoiceWorkcontent=tInvoiceWorkcontentList.get(i);
           params.put("content"+i, Texts.of(tInvoiceWorkcontent.getWorkDescription()+ticket.getWorkArea()).fontSize(12).bold().create());
       }
        // 渲染文本


        params.put("workStartTime",Texts.of(DateUtils.dateTime(ticket.getWorkStartTime())).fontSize(12).bold().create());
        params.put("workEndTime",Texts.of(DateUtils.dateTime(ticket.getWorkEndTime())).fontSize(12).bold().create());
        params.put("urlImg", "C:\\Users\\shi'sen'yuan\\Downloads\\SamplePNGImage_3mbmb.png");
        if(ticket.getWorkUnit()!=null){
            params.put("workUnit", Texts.of(ticket.getWorkUnit().toString()).fontSize(12).bold().create());
        }
        if(ticket.getUserUnit()!=null){
            params.put("userUnit", Texts.of(ticket.getUserUnit().toString()).fontSize(12).bold().create());
        }
        if(ticket.getUserMg()!=null){
            params.put("userMg", Texts.of(ticket.getUserMg().toString()).fontSize(12).bold().create());
        }
        return params;
    };

    /**
     * @param templatePath word模板文件路径
     * @param fileDir      生成的文件存放地址
     * @param fileName     生成的文件名
     * @param paramMap     参数集合
     * @return 返回word生成的路径
     */
    public String createWord(String templatePath, String fileDir, String fileName, Map<String, Object> paramMap) throws IOException {
        Assert.notNull(templatePath, "word模板文件路径不能为空");
        Assert.notNull(fileDir, "生成的文件存放地址不能为空");
        Assert.notNull(fileName, "生成的文件名不能为空");
        File dir = new File(fileDir);
        if (!dir.exists()) {
            logger.info("目录不存在，创建文件夹{}!", fileDir);
            dir.mkdirs();
        }
        String filePath = fileDir +"/"+ fileName;
        logger.info("目录{}!", filePath);
        // 读取模板渲染参数
        InputStream is = getClass().getClassLoader().getResourceAsStream(templatePath);
        XWPFTemplate template = XWPFTemplate.compile(is).render(paramMap);
        try {
            // 将模板参数写入路径
            template.writeToFile(filePath);
            template.close();
        } catch (Exception e) {
            logger.error("生成word异常{}", e.getMessage());
            e.printStackTrace();
        }
        String pathFileName = FileUploadUtils.getPathFileName(RuoYiConfig.getFilePath("/"+ "ticketWord"), fileName);
        return pathFileName;
    }
}
