package org.linlinjava.jz.admin.web;


import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.jz.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.jz.admin.util.MapUtil;
import org.linlinjava.jz.admin.util.SecurityHelper;
import org.linlinjava.jz.core.util.PhoneNumberUtil;
import org.linlinjava.jz.core.util.ResponseUtil;
import org.linlinjava.jz.core.validator.Order;
import org.linlinjava.jz.core.validator.Sort;
import org.linlinjava.jz.db.domain.CustomerClient;
import org.linlinjava.jz.db.domain.JzCalllogRecord;
import org.linlinjava.jz.db.service.CustomerClientService;
import org.linlinjava.jz.db.service.JzCalllogRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Api(value = "Admin-Calllog-Record-Controller", description = "话务记录表")
@RestController
@RequestMapping("/admin/calllogRecord")
@Validated
public class AdminCalllogRecordController {

    private static final Logger logger = LoggerFactory.getLogger(AdminCalllogRecordController.class);

    @Autowired
    private JzCalllogRecordService calllogService;

    @Autowired
    private CustomerClientService customerClientService;


    @RequiresPermissions("admin:calllogRecord:list")
    @RequiresPermissionsDesc(menu = {"电访中心", "话务记录"}, button = "查询")
    @GetMapping("/list")
    public Object list(@RequestParam(required = false) String mobile, @RequestParam(required = false) String callType,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "create_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {

        List<JzCalllogRecord> calllogList = calllogService.querySelective(mobile, callType, page, limit, sort, order);

        //手机号码前三后四隐藏
        for (JzCalllogRecord log : calllogList) {
            log.setMobile(PhoneNumberUtil.HideMobile(log.getMobile()));
        }
        return ResponseUtil.okList(calllogList);
    }

    @RequiresPermissions("admin:calllogRecord:create")
    @RequiresPermissionsDesc(menu = {"电访中心", "话务记录"}, button = "添加")
    @PostMapping("/create")
    public Object createRecord(@RequestBody JzCalllogRecord record) {
        if (record.getCustomerId() != null && record.getCustomerId() == 0) {
            List<CustomerClient> customerClients = customerClientService.findUserIdByMobile(record.getMobile());
            if (customerClients.size() > 0) {
                record.setCustomerId(customerClients.get(0).getId().intValue());
            }
        }
        record.setCreateUser(SecurityHelper.getAdminId());
        return ResponseUtil.ok(calllogService.add(record));
    }

    @RequiresPermissions("admin:calllogRecord:update")
    @RequiresPermissionsDesc(menu = {"电访中心", "话务记录"}, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody JzCalllogRecord record) {
        return ResponseUtil.ok(calllogService.update(record));
    }


    @RequiresPermissionsDesc(menu = {"电访中心", "话务记录"}, button = "批量编辑")
    @PostMapping("/updateList")
    public Object updateList(@RequestBody List<JzCalllogRecord> list) {
        if (list == null) return ResponseUtil.badArgumentValue();

        for (JzCalllogRecord record : list) {
            calllogService.update(record);
        }
        return ResponseUtil.ok();
    }

    @ApiOperation("录音回调")
    @GetMapping("/callBack")
    public Object callBack(HttpServletRequest request) {
        // 将异步通知中收到的待验证所有参数都存放到map中
        final Map<String, String> params = MapUtil.convertRequestParamsToMap(request);
        final String paramsJson = JSON.toJSONString(params);
        logger.info("录音回调通知,{}", paramsJson);

        String recordId = params.get("CallSheetID");
        String fileServer = params.get("FileServer");
        String recordFile = params.get("RecordFile");

        JzCalllogRecord jzCalllogRecord = calllogService.findByRecordId(recordId);
        if (null == jzCalllogRecord) {
            return ResponseUtil.badArgumentValue();
        }
        jzCalllogRecord.setRecordUrl(fileServer + "/" + recordFile);
        int count = calllogService.update(jzCalllogRecord);
        if (count > 0) {
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }


}
