<?php

/**
 * Created by PhpStorm.
 * User: chouchou
 * Date: 2020-4-2
 * Time: 0:17
 */

class openemfkClassAction extends openapiAction
{
    public $data = [];
    public $subdata = [];
    public $model = '';

    const MODEL_NAME = 'emfk';
    const FK_NUMB_PREFIX = 'EM-FK-';
    const TABLE_NAME = 'c_emfk';
    const DETAILS_TABLE_NAME = 'c_emfk_details';
    const DB_PREFIX = 'oa';

    public function initAction()
    {
        //post方式接收接口数据
        m('log')->addlog('电费付款','接收数据:'.$_POST['data']);

        $data = json_decode($_POST['data'], true);
        if (empty($data)) $this->showreturn([], $_POST['data'], '201');

        if (!empty($data['docnum'])) $this->data['docnum'] = $data['docnum']; //如果是编辑则携带编码
        $user = $this->getUser($data['uname']); //获取用户信息
        $data['applicant'] = $data['optname'] =  $user['name'];
        $this->subdata = $this->getSubData($data['details']);

        unset($data['details']);
        unset($data['uname']);

        $this->data = $data;

        //构建主表其他信息
        $this->data['applydt'] = $this->data['optdt'] = $data['date'] ?: date('Y-m-d');
        $this->data['uid'] = $this->data['optid'] = $user['id'];
        $this->data['docnum'] = $this->data['docnum'] ?: $this->getDocNum();
        $this->data['status'] = 0;
        $this->data['amount'] = $this->AmountSum();
    }

    //返回不存在的接口方法
    public function __call($name, $arguments)
    {
        $msg = $name . ' action not found';
        $this->showreturn([], $msg, '201');
    }

    //创建预付款单
    public function createAction()
    {
        $model = m(self::TABLE_NAME);
        $id =$model->insert($this->data);
        if ($id) {
            //插入子表数据
            $details = m(self::DETAILS_TABLE_NAME);
            foreach ($this->subdata as $sub) {
                $sub['mid'] = $id;
                $sub['comid'] = 1;
                $details->insert($sub);
            }
            //启动流程
            $this->goflow($id);
            $this->showreturn(['numb' => $this->data['docnum'], 'id' => $id], '插入数据成功', '200');
        } else $this->showreturn([], $model->getLastSql(), '201');
    }

    public function updateAction()
    {
        $mid = $this->getIdByDocNum($this->data['docnum']);
        if (!$mid) $this->showreturn([], '修改数据失败,不匹配的数据记录', '201');

        $where = 'id=' . $mid;
        unset($this->data['docnum']);
        $res = m(self::MODEL_NAME)->update($this->data, $where);
        if (!$res) $this->showreturn([], '修改数据失败,数据字段异常或字段不匹配', '201');

        $details = m(self::DETAILS_TABLE_NAME);
        //1.获取子表数据,子表数据必须要携带子表id
        //2.查询所有子表ID 如果子表ID存在于 记录中则是修改 否则是新增
        $scount = 0;
        foreach ($this->subdata as $k => $sub) {
            if (empty($sub['id'])) {   //插入操作
                $sub['mid'] = $mid;
                $sub['comid'] = 1;
                $details->insert($sub);
            } else {                //新增
                //如果已经存在的子表数据则修改
                if ($details->getone('id=' . $sub['id'])) {
                    $details->update($sub, 'id=' . $sub['id']);
                } else {
                    $sub['mid'] = $mid;
                    $sub['comid'] = 1;
                    $details->insert($sub);
                }
            }
            $scount++;
        }
        $this->showreturn([], '修改数据成功,子表数据成功修改' . $scount . '条记录', '200');
    }

    private function getUser($username)
    {
        $where = "email='" . $username . "@gonn.com.cn'";
        return $this->db->getone('oa_userinfo', $where);
    }

    private function getSubData($details = [])
    {
        $arr = [];
        foreach ($details as $k => $d) {
            if (!empty($d['id'])) $arr[$k]['id'] = $d['id'];
            $arr[$k]['charge_type'] = $d['charge_type'];
            $arr[$k]['amount'] = $d['amount'];
            $arr[$k]['cbzxid'] = $d['cbzxid'];
        }
        return $arr;
    }

    //子表金额求和
    private function AmountSum()
    {
        $sum = 0;
        foreach ($this->subdata as $v) {
            $sum += $v['amount'];
        }
        return $sum;
    }

    private function getDocNum()
    {
        $ext = self::FK_NUMB_PREFIX . date("Ymd"); //编号前缀
        $where = "`docnum` like '%" . $ext . "%'";
        $mode = m(self::TABLE_NAME);

        $data = $mode->getone($where, 'id,docnum', 'id desc');

        $num = '001'; //编号后缀

        if ($data) {
            $num = (int)substr($data['docnum'], strlen($ext)) + 1;
            if (strlen($num) == 2) {
                $num = '0' . $num;
            } else if (strlen($num) == 1) {
                $num = '00' . $num;
            }
        }
        return $ext . $num;
    }

    private function getIdByDocNum($docnum)
    {
        $data = m(self::TABLE_NAME)->getone("`docnum`='" . $docnum . "'", 'id,docnum');
        return $data['id'] ?: 0;
    }

    //启动流程
    private function goflow($id)
    {
        $mode = m("flow:" . self::MODEL_NAME);
        $mode->initdata(self::MODEL_NAME);
        $mode->loaddata($id);
        $mode->submit();
    }
}