package com.cftech.waybill.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.accounts.service.MpAccountsService;
import com.cftech.core.util.DateFormatUtils;
import com.cftech.order.model.Order;
import com.cftech.order.service.OrderService;
import com.cftech.orderdetail.model.OrderDetails;
import com.cftech.orderdetail.service.OrderDetailsService;
import com.cftech.waybill.model.Waybill;
import com.cftech.waybill.service.WaybillService;
import com.cftech.core.poi.ExcelKit;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.Constants;
import com.cftech.sys.security.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

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


/**
 * 顺丰物流运单Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String WAYBILL_VIEW = "qy:waybill:view"
 * 查看:public static final String WAYBILL_EDIT = "qy:waybill:edit"
 *
 * @author Strive
 * @date: 2020-10-21 15:04
 */
@Slf4j
@Controller
@RequestMapping("/a/waybill")
public class WaybillController {

    public static final String WAYBILL_VIEW = "qy:waybill:view";
    public static final String WAYBILL_EDIT = "qy:waybill:edit";

    @Autowired
    private WaybillService waybillService;

    @Autowired
    private MpAccountsService accountsService;

    //列表页面
    @RequiresPermissions(value = WAYBILL_VIEW)
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        return "waybill/waybilllist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = WAYBILL_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            Waybill waybill = waybillService.fetchByWayBillId(id);
            if (waybill != null) {
                StringBuilder sb = new StringBuilder();
                if (StringUtils.isNoneBlank(waybill.getContact())) {
                    sb.append(waybill.getContact());
                    waybill.setContact(sb.replace(1,2, "*").toString());
                    sb.setLength(0);
                }
                if (StringUtils.isNoneBlank(waybill.getMobile())) {
                    sb.append(waybill.getMobile());
                    waybill.setMobile(sb.replace(3, 7, "****").toString());
                    sb.setLength(0);
                }
                if (waybill.getSendExpressDate() != null) {
                    waybill.setSendExpressDateStr(DateFormatUtils.getDateFormat(waybill.getSendExpressDate(), "yyyy-MM-dd HH:ss"));
                }
                if (waybill.getAcceptExpressDate() != null) {
                    waybill.setAcceptExpressDateStr(DateFormatUtils.getDateFormat(waybill.getAcceptExpressDate(), "yyyy-MM-dd HH:ss"));
                }
            }
            model.addAttribute("data", waybill);
        }
        return "waybill/waybillform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = WAYBILL_EDIT)
    @RequestMapping("/formData")
    @ResponseBody
    public JSONObject formData(Waybill waybill, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            if (waybill != null && waybill.getId() != null) {
                waybill.setUpdateBy(UserUtils.getUser().getId());
                waybillService.update(waybill);
                rtnJson.put("errorNo", 0);
            } else {
                waybill.setAccountsId(accountsId);
                waybill.setDelFlag(false);
                waybill.setAccountsId(UserUtils.getmpaccounts(request));
                waybill.setCreateBy(UserUtils.getUser().getId());
                waybill.setUpdateBy(UserUtils.getUser().getId());
                waybillService.save(waybill);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = WAYBILL_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Waybill waybill, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("t.del_flag", Constants.DEL_FLAG_0);
        conds.equal("t.accounts_id", accountsId);

        if (StringUtils.isNoneBlank(waybill.getNumber())) {
            conds.equal("t.number", waybill.getNumber());
        }

        if (StringUtils.isNoneBlank(waybill.getWaybillNo())) {
            conds.equal("t.waybill_no", waybill.getWaybillNo());
        }

        if (StringUtils.isNoneBlank(waybill.getOrderCode())) {
            conds.equal("o.number", waybill.getOrderCode());
        }

        if (StringUtils.isNoneBlank(waybill.getContact())) {
            conds.like("t.contact", "%" + waybill.getContact() + "%");
        }

        Sort sort = new Sort("t.create_time", OrderType.DESC);

        List<Waybill> list = waybillService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = waybillService.count(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

    //删除数据
    @RequiresPermissions(value = WAYBILL_EDIT)
    @RequestMapping("/delete")
    @ResponseBody
    public JSONObject delete(String id) {
        JSONObject rtnJosn = new JSONObject();
        try {
            waybillService.delete(id);
            rtnJosn.put("errorNo", 0);
        } catch (Exception e) {
            rtnJosn.put("errorNo", 1);
        }
        return rtnJosn;
    }

    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = WAYBILL_VIEW)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response , Waybill waybill) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("t.del_flag", Constants.DEL_FLAG_0);
        conds.equal("t.accounts_id", accountsId);

        if (StringUtils.isNoneBlank(waybill.getNumber())) {
            conds.equal("t.number", waybill.getNumber());
        }

        if (StringUtils.isNoneBlank(waybill.getWaybillNo())) {
            conds.equal("t.waybill_no", waybill.getWaybillNo());
        }

        if (StringUtils.isNoneBlank(waybill.getOrderCode())) {
            conds.equal("o.number", waybill.getOrderCode());
        }

        if (StringUtils.isNoneBlank(waybill.getContact())) {
            conds.like("t.contact", "%" + waybill.getContact() + "%");
        }

        Sort sort = new Sort("t.create_time", OrderType.DESC);
        List<Waybill> list = waybillService.fetchSearchByPage(conds, sort, 0, 0);
        list.forEach(item -> {
            if (StringUtils.equals(item.getFilterResult(), "1")) {
                item.setFilterResult("人工确认");
            } else if (StringUtils.equals(item.getFilterResult(), "2")) {
                item.setFilterResult("可派收");
            } else if (StringUtils.equals(item.getFilterResult(), "3")) {
                item.setFilterResult("不可派收");
            }
            if (StringUtils.isNoneBlank(item.getContact()) && item.getContact().length() >=2) {
                StringBuffer str = new StringBuffer(item.getContact());
                str.replace(1, 2, "*");
                item.setContact(str.toString());
            }
            if (StringUtils.isNoneBlank(item.getMobile())) {
                StringBuffer str = new StringBuffer(item.getMobile());
                str.replace(3, 7, "****");
                item.setMobile(str.toString());
            }

        });
        ExcelKit.$Export(Waybill.class, response).toExcel(list, "顺丰物流单信息");
    }

    @RequestMapping("/templateExcel")
    @RequiresPermissions(value = WAYBILL_VIEW)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        ExcelKit.$Export(Waybill.class, response).toExcel(null, "顺丰物流单信息");
    }

    @RequestMapping("/importExcel")
    @RequiresPermissions(value = WAYBILL_EDIT)
    public String importExcel(HttpServletRequest request, MultipartFile file, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        if (file == null) {
            return list(request, model);
        }
        // 构造临时路径来存储上传的文件
        String uploadPath = System.getProperty("java.io.tmpdir");
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        String fileName = file.getOriginalFilename();
        String filePath = uploadPath + File.separator + fileName;
        File fileTmp = new File(filePath);
        try {
            file.transferTo(fileTmp);
            ExcelKit.$Import().setEmptyCellValue("").readExcel(fileTmp, rowData -> {
                if (!StringUtils.isEmpty(rowData.get(0))) {
                    Waybill waybill = new Waybill();
                    waybill.setAccountsId(accountId);
                    waybillService.save(waybill);
                }
            });
        } catch (IOException e) {
            log.error(e.getMessage());
        }

        return list(request, model);
    }

    /**
     * 订单出库
     * @return
     */
    @RequestMapping("/orderSendOutForWaybill")
    @ResponseBody
    public JSONObject orderSendOutForWaybill(HttpServletRequest request, Long orderId, String datas) {
        return waybillService.orderSendOutForWaybill(request, orderId, datas);
    }

    /**
     * 打印面单
     * @return
     */
    @RequestMapping("/orderPrinterBill")
    @ResponseBody
    public JSONObject orderPrinterBill(HttpServletRequest request, Long orderId) {
        return waybillService.orderPrinterBill(request, orderId);
    }
}
