<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class ThreadsExport implements FromCollection,WithHeadings
{
    protected  $data;

    public function __construct($data,$field)
    {
        $this->data = $data;
        $this->field = $field;
    }

    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        $collection = [];

        foreach ($this->data as $item){
            $contact = $item->contact?$item->contact->phone:'暂无联系人信息';
            $qq = $item->contact?$item->contact->qq:'';
            $email = $item->contact?$item->contact->email:'';
            $company_name = $item->company->company_name;
            $ower_name = $item->ower->real_name;
            $companyWebsite = $item->company->website;
            $legal_person = $item->company->legal_person;
            $reg_capital = $item->company->reg_capital;
            $reg_addr = $item->company->reg_addr;
            $lastest = $item->latestProgress();
            $created_at = $item->created_at;

            $base_coll = [$company_name,$contact];

            if(substr_count($this->field,'qq')) array_push($base_coll,$qq);
            if(substr_count($this->field,'email')) array_push($base_coll,$email);

            if(substr_count($this->field,'ower_name')) array_push($base_coll,$ower_name);
            if(substr_count($this->field,'website')) array_push($base_coll,$companyWebsite);
            if(substr_count($this->field,'legal_person')) array_push($base_coll,$legal_person);
            if(substr_count($this->field,'reg_capital')) array_push($base_coll, $reg_capital);
            if(substr_count($this->field,'reg_addr')) array_push($base_coll,$reg_addr);
            if(substr_count($this->field,'lastest')) array_push($base_coll, $lastest);
            if(substr_count($this->field,'created_at')) array_push($base_coll,$created_at);

            $collection[] = $base_coll;
        }

        return collect($collection);
    }

    public function headings(): array
    {
        $head = ['企业名称','联系方式'];
        if(substr_count($this->field,'qq')) array_push($head,'QQ');
        if(substr_count($this->field,'email')) array_push($head,'Email');

        if(substr_count($this->field,'ower_name')) array_push($head,'线索拥有者');
        if(substr_count($this->field,'website')) array_push($head,'企业网站');
        if(substr_count($this->field,'legal_person')) array_push($head,'法人');

        if(substr_count($this->field,'reg_capital')) array_push($head,'注册资本(万)');
        if(substr_count($this->field,'reg_addr')) array_push($head,'注册地址');

        if(substr_count($this->field,'lastest')) array_push($head,'最新跟进');
        if(substr_count($this->field,'created_at')) array_push($head,'领取时间');

        return $head;
    }
}
