<template>
    <div class="add-business">
        <!-- 自定义步骤条 -->
        <Steps 
            :activeStep="step"
            :allowStepClick="false"
        />
        <div class="first-step-form-wrap" v-show="step===1">
            <el-form 
                :model="firstFormData" 
                :rules="rules"
                ref="firstFormEl" 
                label-width="120px"
                inline
                class="first-step-form"
            >
                <div class="form-line">
                    <el-form-item label="所属区域" prop="areaType">
                        <el-radio-group v-model="firstFormData.areaType">
                            <el-radio label="国内" border>国内</el-radio>
                            <el-radio label="海外" border>海外</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="商家名称" prop="name">
                        <autocomplete
                            ref="auto"
                            v-model="firstFormData.name"
                            :fetch-suggestions="callbackHandle"
                            placeholder="请输入商家名称"
                            @blur="checkCompany"
                            @select="customNameSelect"
                            @focus="checkCompanyfocus"
                            :disabled='inquireSuccess'
                            clearable
                            value-key="value"
                            style="width:360px"
                            :popper-class="isCheck?'el-autocomplete-none':'el-autocomplete-suggestion-data-entry'"
                            class="autocomplete-input"
                        >
                            <span 
                                v-if="firstFormData.name.length > 3" 
                                style="color:#409EFF;cursor: pointer;" slot="suffix"  
                                @click="$refs.auto.search(firstFormData.name)"
                            > 查询</span>
                            <template slot-scope="scope">
                                <div v-if="scope.item.KeyNo">{{scope.item.Name}}</div>
                                <div v-else style="text-align:center">暂无数据</div>		 
                            </template>
                        </autocomplete>
                        <!-- <el-input placeholder="请输入商家名称" v-model="firstFormData.name"/> -->
                    </el-form-item>
                </div>
                <div class="form-line">
                    <el-form-item label="社会信用码" prop="creditCode">
                        <el-input disabled placeholder="请输入社会信用码" v-model="firstFormData.creditCode"/>
                    </el-form-item>
                    <el-form-item label="商家地址" prop="address" v-if="firstFormData.areaType=='国内'">
                        <el-cascader 
                            v-model="firstFormData.address"
                            :props="locationProps"
                            clearable 
                            :options="locationOptions"  
                            @change="selectRegion" 
                            placeholder="请选择客户地址" 
                        />
                    </el-form-item>
                    <el-form-item label="所属国家" prop="nation" v-else>
                        <el-select v-model="firstFormData.nation" placeholder="请选择所属国家" filterable style="width: 360px;">
                            <el-option :label="item.cnName" :value="item.cnName" v-for="item in countryData" :key="item.code" >
                            <div style="display: flex;justify-content: space-between;">
                                <span>{{ item.cnName }}</span>
                                <span style="color: #8492a6; font-size: 13px">{{ item.code }}</span>
                            </div>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
                <div class="form-line">
                    <el-form-item label="决策人" prop="decisionMaker">
                        <el-input placeholder="请输入决策人" v-model="firstFormData.decisionMaker"/>
                    </el-form-item>
                    <el-form-item label="研究团队规模" prop="teamSize">
                        <el-select 
                            v-model="firstFormData.teamSize" 
                            placeholder="请选择研究团队规模"
                            clearable
                        >
                            <el-option
                                v-for="item in teamSizeOpts"
                                :key="item.val"
                                :label="item.label"
                                :value="item.val">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
                <div class="form-line">
                    <el-form-item label="资金规模" prop="fundsize">
                        <el-input placeholder="请输入资金规模" v-model="firstFormData.fundsize"/>
                    </el-form-item>
                    <el-form-item label="所属行业" prop="industry">
                        <el-select 
                            v-model="firstFormData.industry" 
                            placeholder="请选择行业" 
                            clearable
                        >
                            <el-option
                                v-for="item in tradeArr"
                                :key="item.IndustryId"
                                :label="item.IndustryName"
                                :value="item.IndustryId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
                <div class="form-line">
                    <el-form-item label="用户上限" prop="userMax">
                        <el-input type="number" placeholder="请输入用户上限" v-model="firstFormData.userMax"/>
                    </el-form-item>
                    <el-form-item label="所属销售" prop="saller">
                        <el-cascader
                            ref="cascader"
                            v-model="firstFormData.saller"
                            :options="salesArr"
                            :show-all-levels="false"
                            :props="{
                                expandTrigger: 'hover',
                                children: 'Child',
                                emitPath: false,
                                label:'AdminName',
                                value:'AdminId',
                            }"
                            filterable
                            clearable
                            placeholder="请选择销售"
                        />
                    </el-form-item>
                </div>
                
            </el-form>
        </div>
        <div class="second-step-form-wrap" v-show="step===2">
            <el-form 
                :model="secondFormData" 
                :rules="rules"
                ref="secondFormEl" 
                label-width="120px"
                inline
                class="second-step-form"
            >
                <div class="form-line">
                    <el-form-item label="签约日期" prop="signDate">
                        <el-date-picker
                            v-model="secondFormData.signDate"
                            type="date"
                            placeholder="选择日期"
                            value-format="yyyy-MM-dd"
                        />
                    </el-form-item>
                    <el-form-item label="到期日期" prop="expirationDate">
                        <el-date-picker
                            v-model="secondFormData.expirationDate"
                            type="date"
                            placeholder="选择日期"
                            value-format="yyyy-MM-dd"
                        />
                    </el-form-item>
                </div>
                
            </el-form>
        </div>

        <div class="btns-box">
            <el-button style="width:80px" type="primary" v-show="step===1" @click="handleStepSecond">下一步</el-button>
            <el-button style="width:80px" type="primary" v-show="step===1" plain @click="$router.back()">取消</el-button>
            <el-button style="width:80px" type="primary" v-show="step===2" plain @click="step--">上一步</el-button>
            <el-button style="width:80px" type="primary" v-show="step===2" @click="handleAddBusiness">保存</el-button>
        </div>
    </div>
</template>

<script>
import { customInterence,roadshowInterence,businessCustomInterence } from '@/api/api.js'
import autocomplete from "@/components/autocomplete.vue";
import Steps from "./components/Steps.vue";
import {locationOptions} from "@/views/custom_manage/customList/location"
import country from "@/utils/countryData"
export default {
    components: {autocomplete,Steps},
    data() {
        this.countryData = country
        return {
            /* 城市地址数据 */
            locationOptions,
            locationProps:{
                value:'name',
                children:'city',
                label:'name'
            },

            /* 自动输入社会信用码 */
            isCheckCompanyInfo:false, 
			checkCompanyfocusIs:false,
			inquireSuccess:false,
            nameRepeat:false,
			codeRepeat:false,
            isCheck:false,//检查客户弹窗
			repeatId:'',//重复公司id
			repeatName:'',//重复公司类型

            salesArr:[],//销售员数据
            tradeArr:[],//行业数据
            step:1,//第几步

            /* 研究团队规模数据 */
            teamSizeOpts:[
                {
                    val:'50人及以下',
                    label:'50人及以下'
                },
                {
                    val:'200人及以下',
                    label:'200人及以下'
                },
                {
                    val:'超过200人',
                    label:'超过200人'
                }
            ],
            
            rules:{
                areaType:[{ required: true, message: '请选择所属区域', trigger: 'change' },],
                name:[{ required: true, message: '请输入商家名称', trigger: 'blur' },],
                creditCode:[{ required: true, message: '请输入社会信用码', trigger: 'blur' },],
                address:[{ required: true, message: '请选择商家地址', trigger: 'change' },],
                nation:[{ required: true, message: '请选择所属国家', trigger: 'change' },],
                decisionMaker:[{required: true, message: '请输入决策人', trigger: 'blur' },],
                teamSize:[{required: true, message: '请选择研究团队规模', trigger: 'change' },],
                industry:[{required: true, message: '请选择所属行业', trigger: 'change' },],
                userMax:[{required: true, message: '请输入用户上限', trigger: 'blur' },],
                /* signDate:[{required: true, message: '请选择签署日期', trigger: 'change' },],
                expirationDate:[{required: true, message: '请选择签署日期', trigger: 'change' },], */
                saller:[{required: true, message: '请选择所属销售', trigger: 'change' },],
            },

            /* 表单初始值 */
            firstFormData:{
                areaType:'国内',
                name:'',
                creditCode:'',
                address:'',
                nation:'',
                decisionMaker:'',
                teamSize:'',
                fundsize:'',
                industry:'',
                userMax:'',
                saller:''
            },
            secondFormData:{
                signDate:'',
                expirationDate:''
            }
        }
    },
    watch:{
        'firstFormData.areaType':{
            handler(newVal){
                console.log('watch?',newVal)
                if(newVal==='海外'){
                    this.firstFormData.creditCode = 'HZ' + new Date().getTime()
                    // this.firstFormData.address = ['海外','其他市']
                    // this.selectRegion(['海外','其他市'])
                }else{
                    this.firstFormData.creditCode = ''
                    // this.firstFormData.address = []
                }
            }
        }
    },
    created() {
        this.getIndustry()
        this.getSale()
    },
    methods: {
        normalizingParams(params){
            const cascaderNodes = this.$refs.cascader.getCheckedNodes({leafOnly:true})
            const IndustryName = this.tradeArr.find(item=>item.IndustryId===params.industry).IndustryName
            return {
                BusinessName:params.name,
                CreditCode:params.creditCode,
                RegionType:params.areaType,
                Province:params.province,
                City:params.city,
                Nation:params.nation,
                SellerId:Number(cascaderNodes[0]?cascaderNodes[0].value:0),
                SellerName:cascaderNodes[0]?cascaderNodes[0].label:'',
                Leader:params.decisionMaker,
                IndustryId:Number(params.industry),
                IndustryName:IndustryName,
                CapitalScale:params.fundsize,
                ResearchTeamSize:params.teamSize,
                UserMax:Number(params.userMax),
                SigningTime:params.signDate||'',
                ExpiredTime:params.expirationDate||''
            }
        },
        //跳转到第二步
        handleStepSecond(){
            this.$refs.firstFormEl.validate((valid)=>{
                if(valid){
                    const params = this.normalizingParams(this.firstFormData)
                    businessCustomInterence.addBusiness({
                        IsCheck:true,
                        ...params
                    }).then(res=>{
                        if(res.Ret!==200) return 
                        this.step++
                    })
                }
            })
        },
        //保存商家
        handleAddBusiness(){
            this.$refs.secondFormEl.validate((valid)=>{
                if(valid){
                    const params = this.normalizingParams({...this.firstFormData,...this.secondFormData})
                    businessCustomInterence.addBusiness({
                        IsCheck:false,
                        ...params
                    }).then(res=>{
                        if(res.Ret!==200) return 
                        this.$message.success('添加成功')
                        this.$router.push('/businessETAList')
                    })
                }
            })
        },

        async callbackHandle(data,cb) {
            if (data) {
                this.isCheckCompanyInfo =true
                cb([]);
                let res = await customInterence.companyQccSearch({ KeyWord: data});
                if (res.Ret === 200) {
                    this.isCheckCompanyInfo =false;
                    if (res.Data && res.Data.length > 0) {
                        let arr = res.Data.map((item) => {
                            return { value:item.Name, ...item };
                        });
                        cb(arr);
                    }else{
                        cb([{}]);
                        // this.checkCompany()
                    }	
                }	
            }
		},

        checkCompanyfocus(){
			this.checkCompanyfocusIs =true;
			setTimeout(() => {
			    this.checkCompanyfocusIs =false;
			},500)
		},

        //选中后增加社会信用码
		customNameSelect(value) {
			this.firstFormData.creditCode = value.CreditCode
			//this.inquireSuccess = true;
			setTimeout(async()=>{
				this.checkCompany()
			},10)
		},

        /* 客户名称/信用码失焦时校验客户名称是否存在 存在就提示 */
		checkCompany() {	
			setTimeout(()=>{
                if(this.checkCompanyfocusIs) return
                if((!this.firstFormData.name && !this.firstFormData.creditCode) || (this.isCheckCompanyInfo && this.firstFormData.name)) return
                    customInterence.checkCompanyInfo({
                        CompanyName:this.firstFormData.name,
                        CreditCode:this.firstFormData.creditCode
                    }).then(res =>{
                        if(res.Ret === 200){
                            if(res.Data.RepeatStatus > 0) {
                                this.repeatId = res.Data.CompanyId;
                                this.repeatName = res.Data.ProductName;
                                this.nameRepeat = res.Data.RepeatStatus
                                this.codeRepeat = res.Data.Status
                                this.isCheck = true;
                            }else {
                                this.nameRepeat = 0
                                this.isCheck = false;
                            }
                        }
                    })
			},500)
		},

        selectRegion(e){
            this.firstFormData.province=e[0]
            this.firstFormData.city=e[1]
        },
        /* 根据类型获取行业 */
		getIndustry() {
			customInterence.getindustry({
				Classify:'ficc'
			}).then(res => {
				if(res.Ret === 200) {
					this.tradeArr = res.Data.List || [];
				}
			})
		},
        /* 获取销售 */
        async getSale() {
            const res = await roadshowInterence.getSellerList();
            if(res.Ret!==200) return 
            this.salesArr = res.Data.List||[]
            this.salesArr = this.salesArr.map(i=>{
                if(!i.AdminName){
                    i.AdminName = i.GroupName
                }
                if(!i.AdminId){
                    i.AdminId = i.GroupId
                }
                return i
            })
        },
    },
}
</script>

<style lang="scss" scoped>
.add-business{
    padding:30px;
    box-sizing: border-box;
    background-color: #fff;
    min-width: 1100px;
    height: calc(100vh - 120px);
    .first-step-form-wrap,.second-step-form-wrap{
        margin-top:60px;
        border-top: 1px solid #DCDCDC;
        width:70%;
    }
    .el-form{
        .form-line{
            margin:30px 0;
            border-bottom: 1px solid #DCDCDC;
            .el-input,.el-select,.el-cascader,.el-radio-group{
                width:360px;
            }
            .el-radio-group{
                display: flex;
                justify-content: space-between;
                .el-radio{
                    width: 165px;
                    text-align: center;
                }
            }
        }
    }
}
.btns-box{
    position: fixed;
    left: 50%;
    bottom: 100px;
    transform: translateX(-50%);
    width: 200px;
    z-index: 99;
}
</style>