<?php

// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------


namespace app\controller\api\user;

use app\common\repositories\store\CityAreaRepository;
use think\App;
use crmeb\basic\BaseController;
use app\common\model\store\GeoProvince;
use app\common\model\store\GeoCity;
use app\common\model\store\GeoArea;
use app\common\model\store\GeoStreet;
use app\common\model\store\GeoVillage;
use app\common\model\store\GeoBrigade;
use app\validate\api\UserAddressValidate as validate;
use app\common\repositories\user\UserAddressRepository as repository;
use think\exception\ValidateException;

class UserAddress extends BaseController
{
    /**
     * @var repository
     */
    protected $repository;

    /**
     * UserAddress constructor.
     * @param App $app
     * @param repository $repository
     */
    public function __construct(App $app, repository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }


    public function lst()
    {
        return app('json')->success($this->repository->getList($this->request->uid()));
    }

    public function detail($id)
    {
        $uid = $this->request->uid();
        if (!$this->repository->existsWhere(['address_id' => $id, 'uid' => $uid])) {
            return app('json')->fail('地址不存在');
        }
        $addinfo = $this->repository->get($id, $uid);
        $area = [];
        if (!empty($addinfo['province_id'])) {
            $province = GeoProvince::where('province_id', $addinfo['province_id'])->find();
            if ($province) {
                $area[] = [
                    'type' => 'province',
                    'id' => $province->province_id,
                    'level' => 1,
                    'name' => $province->province_name ?? '',
                    'code' => $province->province_code ?? ''
                ];
            }

        }
        if (!empty($addinfo['city_id'])) {
            $city = GeoCity::where('city_id', $addinfo['city_id'])->find();
            if ($city) {
                $area[] = [
                    'type' => 'city',
                    'id' => $city['city_id'],
                    'level' => 2,
                    'name' => $city['city_name'] ?? '',
                    'code' => $city['city_code'] ?? ''
                ];
            }
        }
        if (!empty($addinfo['district_id'])) {
            $district = GeoArea::where('area_id', $addinfo['district_id'])->find();
            if ($district) {
                $area[] = [
                    'type' => 'area',
                    'id' => $district['area_id'],
                    'level' => 3,
                    'name' => $district['area_name'] ?? '',
                    'code' => $district['area_code'] ?? ''
                ];
            }
        }
        if (!empty($addinfo['street_id'])) {
            $street = GeoStreet::where('street_id', $addinfo['street_id'])->find();
            if ($street) {
                $area[] = [
                    'type' => 'street',
                    'id' => $street['street_id'],
                    'level' => 4,
                    'name' => $street['street_name'] ?? '',
                    'code' => $street['street_code'] ?? ''
                ];
            }
        }
        if (!empty($addinfo['village_id'])) {
            $village = GeoVillage::where('village_id', $addinfo['village_id'])->find();
            if ($village) {
                $area[] = [
                    'type' => 'village',
                    'id'   => $village['village_id'],
                    'level' => 5,
                    'name' => $village['village_name'] ?? '',
                    'code' => $village['village_code'] ?? ''
                ];
            }
        }
        $addinfo->areas = $area;
        $addinfo->brigade = [];
        if (!empty($addinfo['brigade_id'])) {
            $brigade = GeoBrigade::where('id', $addinfo['brigade_id'])->find();
            if ($brigade) {
                $addinfo->brigade = [
                    'type' => 'brigade',
                    'id'   => $brigade['id'],
                    'level' => 6,
                    'name' => $brigade['brigade_name'] ?? '',
                    'code' => $brigade['brigade_name'] ?? ''
                ];
            }
        }
        return app('json')->success($addinfo);
    }

    /**
     * @param validate $validate
     * @return mixed
     * @author Qinii
     */
    public function create(validate $validate)
    {
        $data = $this->checkParams($validate);
        if ($data['is_default']) {
            $this->repository->changeDefault($this->request->uid());
        } else {
            if (!$this->repository->defaultExists($this->request->uid())) $data['is_default'] = 1;
        }
        if ($data['address_id']) {
            if (!$this->repository->fieldExists($data['address_id'], $this->request->uid()))
                return app('json')->fail('信息不存在');
            $this->repository->update($data['address_id'], $data);
            return app('json')->success('编辑成功');
        };
        $data['uid'] = $this->request->uid();
        $address = $this->repository->create($data);
        return app('json')->success('添加成功', $address->toArray());
    }

    /**
     * @param $id
     * @param validate $validate
     * @return mixed
     * @author Qinii
     */
    public function update($id, validate $validate)
    {
        if (!$this->repository->fieldExists($id, $this->request->uid()))
            return app('json')->fail('信息不存在');
        $data = $this->checkParams($validate);
        if ($data['is_default']) $this->repository->changeDefault($this->request->uid());
        $this->repository->update($id, $data);
        return app('json')->success('编辑成功');
    }

    /**
     * @param $id
     * @return mixed
     * @author Qinii
     */
    public function delete($id)
    {
        if (!$this->repository->fieldExists($id, $this->request->uid()))
            return app('json')->fail('信息不存在');
        if ($this->repository->checkDefault($id))
            return app('json')->fail('默认地址不能删除');
        $this->repository->delete($id);
        return app('json')->success('删除成功');
    }

    public function editDefault($id)
    {
        if (!$this->repository->fieldExists($id, $this->request->uid()))
            return app('json')->fail('信息不存在');
        $this->repository->changeDefault($this->request->uid());
        $this->repository->update($id, ['is_default' => 1]);
        return app('json')->success('修改成功');
    }

    /**
     * @param validate $validate
     * @return array
     * @author Qinii
     */
    public function checkParams(validate $validate)
    {
        $data = $this->request->params(['address_id', 'real_name', 'phone', 'area', 'detail', 'post_code', 'is_default', 'brigade']);
        $validate->check($data);
        [$province, $city, $district, $street, $village] = ((array)$data['area']) + [null, null, null, null, null];
        $last = $village ?? $street ?? $district ?? $city ?? $province;
        if (!$last) {
            throw new ValidateException('请选择正确的收货地址');
        }
        if (!$this->repository->villageExists('village_code', $last['code'])) {
            throw new ValidateException('地址信息错误');
        }
        $data['province'] = $province['name'];
        $data['province_id'] = $province['id'];
        $data['province_code'] = '';
        if (!empty($data['province_id'])) {
            $province = GeoProvince::where('province_id', $data['province_id'])->find();
            if ($province) {
                $data['province_code'] = $province['province_code'];
            }
        }
        $data['city'] = $city['name'];
        $data['city_id'] = $city['id'];
        $data['city_code'] = '';
        if (!empty($data['city_id'])) {
            $city = GeoCity::where('city_id', $data['city_id'])->find();
            if ($city) {
                $data['city_code'] = $city['city_code'];
            }
        }
        $data['district'] = $district['name'];
        $data['district_id'] = $district['id'];
        $data['district_code'] = '';
        if (!empty($data['district_id'])) {
            $district = GeoArea::where('area_id', $data['district_id'])->find();
            if ($district) {
                $data['district_code'] = $district['area_code'];
            }
        }
        if (isset($street)) {
            $data['street'] = $street['name'] ?? '';
            $data['street_id'] = $street['id'] ?? 0;
            $data['street_code'] = '';
            if (!empty($data['street_id'])) {
                $street = GeoStreet::where('street_id', $data['street_id'])->find();
                if ($street) {
                    $data['street_code'] = $street['street_code'];
                }
            }
        }
        if (isset($village)) {
            $data['village'] = $village['name'] ?? '';
            $data['village_id'] = $village['id'] ?? 0;
            $data['village_code'] = '';
            if (!empty($data['village_id'])) {
                $village = GeoVillage::where('village_id', $data['village_id'])->find();
                if ($village) {
                    $data['village_code'] = $village['village_code'];
                }
            }
        }
        $brigade = $data['brigade'];
        if (isset($brigade)) {
            $data['brigade'] = $brigade['name'] ?? '';
            $data['brigade_id'] = $brigade['id'] ?? 0;
        }
        unset($data['area']);
        return $data;
    }
}