<?php
/**
 * Created by PhpStorm.
 * User: chouchou
 * Date: 2019-6-23
 * Time: 12:05
 */

namespace app\admin\controller;


use app\admin\model\CopyModel;
use app\admin\model\DepartmentModel;
use app\admin\model\ElectricMeter;
use app\admin\model\InvoiceTypeModel;
use app\admin\model\OrderModel;
use app\admin\model\PaymentModel;
use app\admin\model\PayWayModel;
use app\admin\model\ReviewModel;
use app\admin\model\SettleModel;
use app\admin\model\StaffModel;
use app\admin\model\StatementModel;
use app\admin\model\TaxRateModel;
use app\admin\validate\CopyAddValidate;
use app\impexp\controller\Export;
use app\impexp\controller\Import;
use app\station\model\Region;
use app\station\model\Station as StationModel;
use think\App;
use think\Db;
use think\Exception;
use think\facade\Request;
use think\facade\Session;
use app\station\model\Station;


class Copy extends Base
{
    public function __construct(App $app = null)
    {
        parent::__construct($app);
    }

     public function index(){
        $map=[];
                //权限检测
                $user = Session::get('user');
                if(!$user['is_admin']){
                    $permissionData=check_data();
                    if($permissionData){
                    $map[]=$permissionData; 
                    }
                }
                $search_text = Request::get('search_text');
                $search_type = Request::get('search_type'); 
                if($search_text){
                switch ($search_type) {
                    case '1':
                  $this->assign('search_text',$search_text);
                    $map[]=['s.station_name','like',"%$search_text%"];
                  $this->assign('search_type',$search_type);
                        break;
                    case '2':
                  $this->assign('search_text',$search_text);
                    $map[]=['s.station_sp_code','like',"%$search_text%"];
                  $this->assign('search_type',$search_type);
                        break;
                    case '3':
                  $this->assign('search_text',$search_text);
                   $map[]=['s.proj_number','like',"%$search_text%"];
                  $this->assign('search_type',$search_type);
                        break;
                    case '4':
                  $this->assign('search_text',$search_text);
                   $map[]=['em.number','like',"%$search_text%"];
                  $this->assign('search_type',$search_type);
                        break;
                    case '5':
                  $this->assign('search_text',$search_text);
                   $map[]=['em.qrcode','like',"%$search_text%"];
                  $this->assign('search_type',$search_type);
                        break;
                    }
               }else{
                  $this->assign('search_type','');
                  $this->assign('search_text','');
               }
               //区域
                  $area_id = Request::get('area_id');
                 if($area_id){
                     $map[] = ['s.area_id','=',$area_id];
                     $this->assign('area_id',$area_id);
                 }else{
                      $this->assign('area_id','');
                 }
                 //缴费状态
                  $pay_status = Request::get('pay_status');
                 if($pay_status && $pay_status<2){
                     $map[] = ['o.status','=',$pay_status];
                     $this->assign('pay_status',$pay_status);
                 }else{
                      $this->assign('pay_status',2);
                 }

                //抄表时间查询条件
                $dateStart = strtotime(Request::get('date_start'));
                $dateEnd = strtotime(Request::get('date_end'));
                //区间查询
                if( !empty($dateStart) && !empty($dateEnd) ){
                    $map[] = ['copy.current_time','between',[$dateStart,$dateEnd]];
                    $this->assign('date_start',Request::get('date_start'));
                    $this->assign('date_end',Request::get('date_end'));
                } elseif (!empty($dateStart) && empty($dateEnd)){
                    $map[] = ['copy.current_time','>',$dateStart]; 
                    $this->assign('date_start',Request::get('date_start'));
                    $this->assign('date_end','');  
                } elseif (empty($dateStart) && !empty($dateEnd)){
                    $map[] = ['copy.current_time','<',$dateEnd]; 
                    $this->assign('date_end',Request::get('date_end'));  
                    $this->assign('date_start',''); 
                }else{
                    $this->assign('date_start','');
                    $this->assign('date_end','');  
                }
                $page = Request::get('page')?Request::get('page'):1;

                $limit = Request::get('limit')?Request::get('limit'):10;
                $copy= new CopyModel;
                $identity = (new Staff)->getIdentity();

                $copyList= $copy->getCopyList($map,$page,$limit);
                foreach ($copyList as $key => $v) {
                       $copyList[$key]['identity']=$identity;
                }
                $copyCount= $copy->getCopyListCount($map);
                if(Request::get('page')){
                return ['code'=>0,'msg'=>'','count'=>$copyCount,'data'=>$copyList];
                }

        $this->assign('identity',$identity);
        $this->assign('regions',getTree((new ElectricMeter)->regions()));
        return $this->fetch();
     }
    public function search(){

        //区域
        $regions = Region::field('id,region_name')->select()->toArray();
        //页码
        $pageNow = Request::get('page',1);

        //身份信息
        $identity = (new Staff)->getIdentity();

        //查询条件信息
        $condition = '';

        //如果已经查询过 则从session取出查询条件与检索信息
        if($pageNow > 1){
            $map = Session::get('cp_map');
            $condition = Session::get('cp_condition');
        } else {
            //获取查询条件
            $type = Request::post('search_type');
            $text = Request::post('search_text');
            //区域
            $area_id = Request::post('area') + 0;

            switch ($type){
                case 1:
                    $type = 's.station_name';
                    $condition .= '站名: ';
                    break;
                case 2:
                    $type = 's.station_sp_code';
                    $condition .= '站号: ';
                    break;
                case 3:
                    $type = 's.proj_number';
                    $condition .= '项目编号: ';
                    break;
                case 4:
                    $type = 'em.number';
                    $condition .= '电表识别号: ';
                    break;
                case 5:
                    $type = 'er.qrcode';
                    $condition .= '机房二维码: ';
                    break;
            }

            //获取查询条件 1
            if( !empty($text) ){
                $map[] =  [$type,'like',"%".$text."%"];
                $condition .= "<span style='color:#FFB800'> " .$text . " </span>";
            } else {
                $condition .= " 默认 ";
            }


            //获取查询条件 2区域
            if( $area_id > 0 ){
                $region = '';
                foreach ($regions as $v){
                    if($v['id'] == $area_id) $region = $v;
                }
                $map[] = ['s.area_id','=',$area_id];
                $condition .= " + 区域: <span style='color:#FFB800'>". $region['region_name'] ."</span>";
            } else {
                $condition .= " + 区域: 默认 ";
            }


            //抄表时间查询条件
            $dateStart = strtotime(Request::post('date_start'));
            $dateEnd = strtotime(Request::post('date_end'));

            //区间查询
            if( !empty($dateStart) && !empty($dateEnd) ){
                $map[] = ['copy.current_time','between',[$dateStart,$dateEnd]];  //区间查询
                $condition .= " + 时间 : ".Request::post('date_start') ." ---- ".Request::post('date_end');
            } elseif (!empty($dateStart) && empty($dateEnd)){
                $map[] = ['copy.current_time','>',$dateStart];               //大于开始时间
                $condition .= " + 时间 : 在 ".Request::post('date_start')."之后 ";
            } elseif (empty($dateStart) && !empty($dateEnd)){
                $map[] = ['copy.current_time','<',$dateEnd];              //小于结束时间
                $condition .= " + 时间 : 在 ".Request::post('date_end')."之前 ";
            }

            //结算条件
            $payStatus = Request::post('pay_status');
             if(is_numeric($payStatus) && $payStatus > 0){
                $map[] = ['o.status','=',$payStatus];
                $condition .= " + 已缴费 ";
            } else if(is_numeric($payStatus) && $payStatus == 0) {
                $map[] = ['o.status','=',$payStatus];
                $condition .= " + 未缴费";
            } else if($payStatus == '全部'){
                $condition .= " + 全部缴费状态";
            }

            //资源权限检查
            $user = Session::get('user');
            if(!$user['is_admin'] && $identity != 5){
                if(config('admin.search_area') == 1){
                    $staff = StaffModel::get($user['user_id']);
                    //通过员工的部门id查询 员工所在部门以及下属部门的所有抄表单数据
                    $dIds = (new DepartmentModel)->getNodeIds($staff->d_id);

                    //查询该部门下属所有员工ID
                    $sIds = StaffModel::field('id')->where('d_id','in',$dIds)->select()->toArray();
                    $sIdArr = [];
                    foreach ($sIds as $id){
                        $sIdArr[] = $id['id'];
                    }
                    //部门以及下属部门所有抄表单ID
                    $iDs = CopyModel::field('id')->where('staff_id','in',$sIdArr)->select()->toArray();
                    $idArr = [];
                    foreach ($iDs as $id){
                        $idArr[] = $id['id'];
                    }
                    //查询所属部门所属的抄表单ID
                    $map[] = ['copy.id','in',$idArr];
                }
            }
        }

        //查询显示结果
        if(isset($map) && !empty($map)){
            Session::set('cp_map',$map);
            Session::set('cp_condition',$condition);
            $list = CopyModel::list($pageNow,'',$map);
        }
        else{
            $list = CopyModel::list($pageNow);
        }

        $page = $list->render();
        $this->assign('identity',$identity);
        $this->assign('condition',$condition ?: '默认条件');
        $this->assign('regions',$regions);
        $this->assign('page',$page);
        $this->assign('data',$list);

        return $this->fetch('index');
    }

    //显示添加抄表单
    public function create($id){

        //基本信息查询
        $em =  ElectricMeter::get($id);
        $staffs =StaffModel::getCurrentStaffsByDepartment();
        $station = Station::get(['station_id'=>$em->station_id]);

        //上一次的抄表单
        $cp = CopyModel::where(['em_id'=>$em->id])->order('current_time desc,id desc')->find();

        if ($cp)  $cp = $cp->toArray();

        //第一次抄表
        if(empty($cp)){
            $cp['before_number'] = $em->init_degree ?: 0;
            $cp['before_time'] = date('Y-m-d',$em->first_cp_date) ?: date('Y-m-d',$em->create_time);
            if($em->emt_id == 2 || $em->emt_id == 4)
                $cp['before_amount'] = $em->init_amount ?: 0;

            $cp['current_number'] = '';
            $cp['current_time'] = date('Y-m-d',time());
            $cp['photo_id'] = '';
            $cp['photo_src'] = '';
        } else {
            $cp['before_number'] = $cp['current_number'];
            $cp['before_time'] = $cp['current_time'] ?: date('Y-m-d',$em->first_cp_date);
            $cp['before_amount'] = $cp['current_amount'];
            $cp['current_amount'] = '';
            $cp['current_number'] = '';
            $cp['cp_id'] = '';
        }

        //查询上一次抄表日期
        $this->assign('staffs',$staffs);
        $this->assign('station',$station);
        $this->assign('em',$em);
        $this->assign('cp',$cp);
        return $this->fetch('copy');
    }
    //保存抄表单
    public function store(){
        $data = Request::post();
        $validate = new CopyAddValidate;

        //设置验证场景为后付费表
        $scene = 'postpaid';

        //如果是预付费表
        if(Request::post('emt_id') == 2 || Request::post('emt_id')==4) {
            $scene = 'prepaid';
        }
        if(!$validate->scene($scene)->check($data)){
            return jsonErr($validate->getError());
        }

        $cp = CopyModel::create($data);

        if($cp->id){
            //生成订单
            $oData = [
                'order_id' => Order::serial(),
                'cp_id' => $cp->id,
                'em_id'=> $cp->em_id
            ];
            if(OrderModel::create($oData))
                return jsonSuc('添加成功',$cp->id);
            else
                return jsonErr('生成流水错误');
        } else {
            return jsonErr('表单添加失败');
        }
    }

    public function detail($id){
        //获取抄表单信息&&基站电表基本信息
        $copy = CopyModel::getCopyEmInfoByCid($id);

        //获取订单状态
        $state = (new Order)->state($copy['order_id']);
        $payways = PayWayModel::select()->toArray();
        $taxRates = TaxRateModel::select()->toArray();
        $invoiceType = InvoiceTypeModel::select()->toArray();

        $this->assign('invoice_type',$invoiceType);
        switch ($state){
            case 1:
                break;
            case 3:
                //获取statement
                $statement = StatementModel::getStatementByCpId($id);
                $this->assign('statement',$statement);
                break;
            case 6:
                $statement = StatementModel::getStatementByCpId($id);
                $this->assign('statement',$statement);

                $this->assign('taxrates',$taxRates);
                $this->assign('payways',$payways);
                $payment =  PaymentModel::getPaymentByCpId($id);
                $this->assign('payment',$payment);
                $paymentuser = StaffModel::getStaffNameById($payment->pay_sid);
                $this->assign('paymentuser',$paymentuser);
                break;
            case 7:
                $statement = StatementModel::getStatementByCpId($id);
                $this->assign('statement',$statement);

                $settle =  SettleModel::getSettleByCpId($id);
                $this->assign('settle',$settle);
                break;
            case 10:
                $statement = StatementModel::getStatementByCpId($id);
                $this->assign('statement',$statement);

                $this->assign('taxrates',$taxRates);
                $this->assign('payways',$payways);
                $payment =  PaymentModel::getPaymentByCpId($id);

                $this->assign('payment',$payment);
                $paymentuser = StaffModel::getStaffNameById($payment->pay_sid);
                $this->assign('paymentuser',$paymentuser);

                $settle =  SettleModel::getSettleByCpId($id);
                $settleuser = StaffModel::getStaffNameById($settle->settle_sid);
                $this->assign('settleuser',$settleuser);
                $this->assign('settle',$settle);
                break;
        }


        $this->assign('copy',$copy);
        $this->assign('state',$state);
        return $this->fetch('detail');
    }

    public function upPhoto(){
        $file = Request::file('cp_photo');
        $upload = new Upload($file,1);
        $result = $upload->upload();

        if($result){
            return jsonSuc('照片上传成功',$result);
        } else {
            return jsonErr($result);
        }
    }

    public function del(){
        $order  =  OrderModel::get(['cp_id'=>Request::post('id')]);
        $user = session('user');
        if($user['is_admin']){
             return jsonErr('管理员无法删除数据');die;
        }
        if($order){
            // 启动事务
            Db::startTrans();
            try {


                $reivew = new ReviewModel;
                $reivew->staff_id = (new Staff())->getCurrentUser()->id ?: 999;
                $reivew->cp_id = $order->cp_id;
                $reivew->action = 4;
                $reivew->result = 1;
                $reivew->message = '员工: '.(new Staff())->getCurrentUser()->name ?: 'admin'.
                    ' 在: '.date('Y-m-d') .
                    '流水单号是:'. $order->order_id .' 抄表单号是:' . $order->cp_id .' 删除成功';
                $reivew->save();


                Db::table('copy')->delete($order->cp_id);
                if($order->statement_id)
                    Db::table('statement')->delete($order->statement_id);
                if($order->payment_id)
                    Db::table('payment')->delete($order->payment_id);
                if($order->settle_id)
                    Db::table('settle')->delete($order->settle_id);

                Db::table('order')->delete($order->id);
                Db::commit();


                return jsonSuc('删除成功');
            } catch (Exception $e) {
                Db::rollback();
                $reivew = new ReviewModel;
                $reivew->staff_id = (new Staff())->getCurrentUser()->id ?: 999;
                $reivew->cp_id = $order->cp_id;
                $reivew->action = 4;
                $reivew->result = 0;
                $reivew->message = '员工: '.(new Staff())->getCurrentUser()->name ?: 'admin' .
                    ' 在: '.date('Y-m-d') .
                    '流水单号是:'. $order->order_id .' 抄表单号是:' . $order->cp_id .' 删除失败';
                $reivew->save();
                return jsonErr('删除异常,请联系管理员');
            }
        } else {
            return jsonErr('资源不存在,无法删除,请联系管理员');
        }
    }


    public function import(){
        $filename = 'cp_file';
        $result = (new Import)->importXls($filename);
        return jsonSuc('导入完毕',$result);
    }

    public function importOnly(){
        $filename = 'cp_file';
        $result = (new Import)->importXls($filename,true);
        return jsonSuc('导入完毕',$result);
    }
    public function export(){
        $ex = new Export();
        $ex->ExportExl();
    }
}