package com.cftech.pay.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.mchaccounts.mch.model.MchAccounts;
import com.cftech.pay.model.PayRecord;
import com.cftech.pay.service.PayRecordService;
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.model.UserRole;
import com.cftech.sys.security.PermissionSign;
import com.cftech.sys.security.UserUtils;
import lombok.extern.slf4j.Slf4j;
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.util.StringUtils;
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 PAYRECORD_VIEW = "qy:payRecord:view"
 * 查看:public static final String PAYRECORD_EDIT = "qy:payRecord:edit"
 *
 * @author Kangliang
 * @date: 2017-05-16 13:04
 */
@Slf4j
@Controller
@RequestMapping("/a/payRecord")
public class PayRecordController {

    public static final String PAYRECORD_VIEW = "qy:payRecord:view";
    public static final String PAYRECORD_EDIT = "qy:payRecord:edit";

    @Autowired
    private PayRecordService payRecordService;


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

    //编辑页面（新增、修改）
    @RequiresPermissions(value = PAYRECORD_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            PayRecord payRecord = payRecordService.fetchById(id);
            model.addAttribute("data", payRecord);
        }
        return "payRecord/payRecordform";
    }

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

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

        // 从环境中做与商户好隔离的操作
        List<String> userMchAccounts = UserUtils.getUserMchAccounts();

        conds.in("mch_id",userMchAccounts.toArray());
        if (!StringUtils.isEmpty(payRecord.getSrcid())) {
            conds.like("srcid", payRecord.getSrcid());
        }
        if (!StringUtils.isEmpty(payRecord.getSrctype())) {
            conds.like("srctype", payRecord.getSrctype());
        }
        if (!StringUtils.isEmpty(payRecord.getMch_id())) {
            conds.like("mch_id", payRecord.getMch_id());
        }
        if (!StringUtils.isEmpty(payRecord.getErr_code())) {
            conds.like("err_code", payRecord.getErr_code());
        }
        if (!StringUtils.isEmpty(payRecord.getErr_code_des())) {
            conds.like("err_code_des", payRecord.getErr_code_des());
        }
        if (!StringUtils.isEmpty(payRecord.getOpenid())) {
            conds.like("openid", payRecord.getOpenid());
        }
        if (!StringUtils.isEmpty(payRecord.getTrade_type())) {
            conds.like("trade_type", payRecord.getTrade_type());
        }
        if (!StringUtils.isEmpty(payRecord.getIs_subscribe())) {
            conds.like("is_subscribe", payRecord.getIs_subscribe());
        }
        if (!StringUtils.isEmpty(payRecord.getBank_type())) {
            conds.like("bank_type", payRecord.getBank_type());
        }
        if (!StringUtils.isEmpty(payRecord.getTotal_fee())) {
            conds.like("total_fee", payRecord.getTotal_fee());
        }
        if (!StringUtils.isEmpty(payRecord.getFee_type())) {
            conds.like("fee_type", payRecord.getFee_type());
        }
        if (!StringUtils.isEmpty(payRecord.getCash_fee())) {
            conds.like("cash_fee", payRecord.getCash_fee());
        }
        if (!StringUtils.isEmpty(payRecord.getCash_fee_type())) {
            conds.like("cash_fee_type", payRecord.getCash_fee_type());
        }
        if (!StringUtils.isEmpty(payRecord.getTransaction_id())) {
            conds.like("transaction_id", payRecord.getTransaction_id());
        }
        if (!StringUtils.isEmpty(payRecord.getOut_trade_no())) {
            conds.like("out_trade_no", payRecord.getOut_trade_no());
        }
        if (!StringUtils.isEmpty(payRecord.getAttach())) {
            conds.equal("attach", payRecord.getAttach());
        }
        if (!StringUtils.isEmpty(payRecord.getTime_end())) {
            conds.equal("time_end", payRecord.getTime_end());
        }
        Sort sort = new Sort("create_time", OrderType.DESC);

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

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

    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = PAYRECORD_VIEW)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        Long accountId = UserUtils.getmpaccounts(request);
        Sort sort = new Sort("create_time", OrderType.ASC);
        Conds conds = new Conds();
        conds.equal("del_flag", 0);
        conds.equal("accounts_id", accountId);
        List<PayRecord> list = payRecordService.fetchSearchByPage(conds, sort, 0, 0);
        ExcelKit.$Export(PayRecord.class, response).toExcel(list, "支付记录信息");
    }

    @RequestMapping("/templateExcel")
    @RequiresPermissions(value = PAYRECORD_VIEW)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        ExcelKit.$Export(PayRecord.class, response).toExcel(null, "支付记录信息");
    }

    @RequestMapping("/importExcel")
    @RequiresPermissions(value = PAYRECORD_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 storeFile = new File(filePath);
        try {
            file.transferTo(storeFile);
            ExcelKit.$Import().readExcel(storeFile, rowData -> {
                if (!StringUtils.isEmpty(rowData.get(0))) {
                    PayRecord payRecord = new PayRecord();
                    payRecord.setAccountsId(accountId);
                    payRecordService.save(payRecord);
                }
            });
        } catch (IOException e) {
            log.error(e.getMessage());
        }

        return list(request, model);
    }

}
