<template>
<view class="bg">
<view class="scrollview">
    <u--form :rules="rules" labelPosition="left" :model="form"  ref="uForm">
        <view class="formItemTitle">基本信息（必填）</view>
        
        <u-form-item class="formItem" prop="name" :labelWidth="labelWidth" label="供应商名称"  borderBottom >
            <u--input :input-align="inputaligh" placeholder="填写供应商名称" v-model="form.name" border="none" clearable ></u--input>
        </u-form-item>
        <u-form-item class="formItem" prop="city" :labelWidth="labelWidth" label="供应商所在地"  borderBottom >
            <view class="selectInput">
                <u--input @click="cityShow=true" :disabled="true" :input-align="inputaligh" placeholder="选择所在地区" v-model="form.cityName" border="none" ></u--input>
                <view @click="cityShow=true"><u-icon name="arrow-right"></u-icon></view>
            </view>
        </u-form-item>
        <u-form-item class="formItem" prop="address" :labelWidth="labelWidth" label="详细地址"  borderBottom >
            <u--input :input-align="inputaligh" placeholder="填写详细地址" v-model="form.address" border="none" clearable ></u--input>
        </u-form-item>

        <view class="margin20"></view>
        <u-form-item class="formItem" prop="category" :labelWidth="labelWidth" label="主营类目"  borderBottom >
            <view class="selectInput">
                <u--input @click="categoryShow=true" :disabled="true" :input-align="inputaligh" placeholder="主营类目" v-model="form.categoryName" border="none" clearable ></u--input>
                <view @click="categoryShow=true"><u-icon name="arrow-right"></u-icon></view>
            </view>
        </u-form-item>

        <view class="margin20"></view>
        <u-form-item class="formItem" prop="businessLicenseName" :labelWidth="labelWidth" label="营业注册名称"  borderBottom >
            <u--input :input-align="inputaligh" placeholder="填写营业执照上企业名称" v-model="form.businessLicenseName" border="none" clearable ></u--input>
        </u-form-item>
        <u-form-item class="formItem" prop="businessLicenseNo" :labelWidth="labelWidth" label="营业执照号"  borderBottom >
            <u--input :input-align="inputaligh" placeholder="请填写营业执照注册号" v-model="form.businessLicenseNo" border="none" clearable ></u--input>
        </u-form-item>
        <u-form-item class="formItem" prop="businessLicense" :labelWidth="labelWidth" label="营业执照照片"  borderBottom >
            <view class="selectInput">
                <u-upload
                    :fileList="fileList1"
                    @afterRead="afterRead"
                    @delete="deletePic"
                    name="1"
                    multiple
                    :maxCount="1"
                ></u-upload>
                <view style="color: #0084ff;font-size: 28rpx;" @click="openPopup(1)">查看示例</view>
            </view>
        </u-form-item>

        <view class="margin20"></view>
        <u-form-item class="formItem" prop="legalPersonName" :labelWidth="labelWidth" label="法人姓名"  borderBottom >
            <u--input :input-align="inputaligh" placeholder="填写法人姓名" v-model="form.legalPersonName" border="none" clearable ></u--input>
        </u-form-item>
        <u-form-item class="formItem" prop="legalPersonCardNo" :labelWidth="labelWidth" label="法人身份证号"  borderBottom >
            <u--input :input-align="inputaligh" placeholder="填写法人身份证号" v-model="form.legalPersonCardNo" border="none" clearable ></u--input>
        </u-form-item>
        <u-form-item class="formItem" prop="cardNoFront" :labelWidth="labelWidth" label="法人身份证照片 （正面）"  borderBottom >
            <view class="selectInput">
                <u-upload
                    :fileList="fileList2"
                    @afterRead="afterRead"
                    @delete="deletePic"
                    name="2"
                    multiple
                    :maxCount="1"
                ></u-upload>
                <view style="color: #0084ff;font-size: 28rpx;" @click="openPopup(2)">查看示例</view>
            </view>
        </u-form-item>
        <u-form-item class="formItem" prop="cardNoReverse" :labelWidth="labelWidth" label="法人身份证照片 （反面）"  borderBottom >
            <view class="selectInput">
                <u-upload
                    :fileList="fileList3"
                    @afterRead="afterRead"
                    @delete="deletePic"
                    name="3"
                    multiple
                    :maxCount="1"
                ></u-upload>
                <view style="color: #0084ff;font-size: 28rpx;" @click="openPopup(3)">查看示例</view>
            </view>
        </u-form-item>

        <view class="margin20"></view>
        <u-form-item class="formItem" prop="contact" :labelWidth="labelWidth" label="联系人"  borderBottom >
            <u--input :input-align="inputaligh" placeholder="输入联系人" v-model="form.contact" border="none" clearable ></u--input>
        </u-form-item>
        <u-form-item class="formItem" prop="phone" :labelWidth="labelWidth" label="联系电话"  borderBottom >
            <u--input :input-align="inputaligh" placeholder="输入联系电话" v-model="form.phone" border="none" clearable ></u--input>
        </u-form-item>
        <u-picker ref="uPicker" @cancel="cityShow=false" keyName="name"  :show="cityShow" :columns="cityColumns" @confirm="cityPickerConfirm" @change="citypickerchange"></u-picker>
        <u-picker @cancel="categoryShow=false" :show="categoryShow" keyName="dictValue" :columns="categoryColumns" @confirm="categoryPickerConfirm"></u-picker>
    </u--form>
    <u-popup :closeable='true' :round="10" :show="popupShow" @close="close" @open="open">
        <view class="popupView">
            <view class="popupImg">
                <u--image width="500rpx" height="326rpx" :src="popupImgurl" ></u--image>
            </view>
        </view>
        <view class="popupViewText">
            {{ popupText }}
        </view>
        <view class="w700 btnflex">
            <u-button  shape="circle" size="medium" type="primary" 
            @click="close">{{ popupBtn }}</u-button>
        </view>
    </u-popup>
    <view style="height: 100rpx;"></view>
</view>

<view class="btnbox" style="left: 24rpx;">
    <!-- <view @click="submit('dosave')" class="btn">
        保存
    </view> -->
    <view @click="submit('submit')" class="btn2">
        提交审核
    </view>
</view>
</view>
</template>

<script>
import {
    getAreaList,myInfo,getCategoryList,settledVendor
    } from '@/http/api/common.js'
import env from "@/http/config/config.js"
import {toastFunc} from '@/pages/util/util.js'
export default {

data() {
    return {
        form:{
            "name": "",
            "contact": "",
            "phone": "",
            "businessLicense": "",
            "cardNoFront": "",
            "cardNoReverse": "",
            "address": "",
            "city": "",
            "cityName": "",
            "category": "",
            "categoryName": "",
            "businessLicenseName": "",
            "businessLicenseNo": "",
            "legalPersonName": "",
            "legalPersonCardNo": ""
        },
        
        rules: {
            'name': {
                type: 'string',
                required: true,
                message: '填写供应商名称',
                trigger: ['blur', 'change']
            },
            'city': {
                type: 'string',
                required: true,
                message: '请选择所在地区',
                trigger: ['blur', 'change']
            },
            'address': {
                type: 'string',
                required: true,
                message: '请填写详细地址',
                trigger: ['blur', 'change']
            },
            'category': {
                type: 'string',
                required: true,
                message: '请选择主营类目',
                trigger: ['blur', 'change']
            },
            'businessLicenseName': {
                type: 'string',
                required: true,
                message: '请填写营业执照上企业名称',
                trigger: ['blur', 'change']
            },
            'businessLicenseNo': {
                type: 'string',
                required: true,
                message: '请填写营业执照注册号',
                trigger: ['blur', 'change']
            },
            'businessLicense': {
                type: 'string',
                required: true,
                message: '请上传营业执照照片',
                trigger: ['blur', 'change']
            },
            'legalPersonName': {
                type: 'string',
                required: true,
                message: '请填写法人姓名',
                trigger: ['blur', 'change']
            },
            'legalPersonCardNo': {
                type: 'string',
                required: true,
                message: '请填写法人身份证号',
                trigger: ['blur', 'change']
            },
            'cardNoFront': {
                type: 'string',
                required: true,
                message: '请上传法人身份证照片 （正面）',
                trigger: ['blur', 'change']
            },
            'cardNoReverse': {
                type: 'string',
                required: true,
                message: '请上传法人身份证照片 （正面）',
                trigger: ['blur', 'change']
            },
            'contact': {
                type: 'string',
                required: true,
                message: '请输入联系人',
                trigger: ['blur', 'change']
            },
            'phone':[ 
                {
                    type: 'string',
                    required: true,
                    message: '请输入联系电话',
                    trigger: ['blur', 'change']
                },
                {
                    validator: (rule, value, callback) => {
                        return uni.$u.test.mobile(value);
                    },
                    message: '手机号码格式不正确',
                    // 触发器可以同时用blur和change
                    trigger: ['blur'],
                }
            ]
        },
        inputaligh:'right',
        fileList1:[],
        fileList2:[],
        fileList3:[],
        fileList:[],
        file:[],
        labelWidth:140,
        popupShow:false,
        popupText:'',
        popupBtn:'上传营业执照',
        popupImgurl:'',
        cityShow:false,
        cityloading:false,

        cityColumns: [],
        columnData: [],

        categoryShow:false,
        categoryColumns: [],
        showType:'1',
    }
},
components: {
    
},

onLoad(e) {
    this.getCategoryList()
    this.getAreaList(2)
},
onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.uForm?.setRules(this.rules)
},

methods: {
    async getCategoryList(){
        let res = await getCategoryList()
        
        this.categoryColumns.push(res.data.data)

    },
    //获取城市列表
    async getAreaList(level,parentId=''){
        let res = await getAreaList({
            level,
            parentId
        })
        this.cityColumns.push(res.data.data) 
        await this.getColumnData(3,res.data.data[0].id)

        const picker = this.$refs.uPicker
        picker.setColumnValues(1, this.columnData[0])
    },
    //获取地区列表
    async getColumnData(level,parentId=''){
        this.cityloading = true
        let res = await getAreaList({
            level,
            parentId
        })
        this.cityloading = false
        
        this.columnData.push(res.data.data)
    },
    cityPickerConfirm(e) {
        console.log('confirm',e.value)
        console.log('city',e.value[1].id)

        this.form.city = e.value[1].id
        this.form.cityName = e.value[1].name
        this.cityShow = false
    },
    async citypickerchange(e){
        const {
            columnIndex,
            index,
            // 微信小程序无法将picker实例传出来，只能通过ref操作
            picker = this.$refs.uPicker
        } = e
        if (columnIndex == 0) {
            this.columnData = []
            await this.getColumnData(3, this.cityColumns[0][index].id)
            picker.setColumnValues(1, this.columnData[0])
        }
    },

    openPopup(type) {
        if (type == 1) {
            this.popupText = '请参考图示提供营业执照，四角完整，确保证内容文字清晰可见，证件本身无残缺；上传图片要求：支持png、jpg、jpeg格式，1024MB内'
            this.popupImgurl = '/static/myinfo/img_yingyezhiz.png'
            this.popupBtn = '上传营业执照'
        }else if (type == 2) {
            this.popupText = '请参考图示提供法人身份证正反面照，四角完整、照片清晰、身份证原件、扫描件或复印件上传图片要求：支持png、jpg、jpeg格式，1024MB内'
            this.popupImgurl = '/static/myinfo/img_shenfzzm.png'
            this.popupBtn = '上传身份证正面'
        }else{
            this.popupText = '请参考图示提供法人身份证正反面照，四角完整、照片清晰、身份证原件、扫描件或复印件上传图片要求：支持png、jpg、jpeg格式，1024MB内'
            this.popupImgurl = '/static/myinfo/img_shenfzfm.png'
            this.popupBtn = '上传身份证反面'
        }

        this.popupShow = true
        // console.log('open');
    },
    close() {
        this.popupShow = false
        // console.log('close');
    },
    categoryPickerConfirm(e) {
        console.log('confirm', e.value[0])
        this.form.category = e.value[0].dictKey
        this.form.categoryName = e.value[0].dictValue
        this.categoryShow = false
    },
   
    async getmyInfo(){
        let res = await myInfo()
        if (res.data.code == 200) {
        this.form.username = res.data.data.nickName

        this.fileList1.push({
            url:res.data.data.image
        })
        
        }
    },
    async submit(type){
        this.form.businessLicense = this.fileList1[0].url //营业执照
        this.form.cardNoFront = this.fileList2[0].url  //身份证正面
        this.form.cardNoReverse = this.fileList3[0].url //身份证反面

        this.$refs.uForm.validate().then(async res1 => {
            console.log(res1);
            // if (type == 'dosave') {
            //     //保存
            // }else{

            //     //提交
            // }
            let res = await settledVendor(this.form)
            if (res.data.code == 200) {
                uni.navigateTo({
                    url: '/supplierPages/pages/supplier/supplierSuccess'
                });
            }
        }).catch(errors => {
            // uni.$u.toast('校验失败')
        })
    },
    // 删除图片
    deletePic(event) {
        this[`fileList${event.name}`].splice(event.index, 1)
    },
    // 新增图片
    async afterRead(event) {
        // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
        console.log('event',event);
        let lists = [].concat(event.file)
        let fileListLen = this[`fileList${event.name}`].length
        lists.map((item) => {
            this[`fileList${event.name}`].push({
                ...item,
                status: 'uploading',
                message: '上传中'
            })
        })
        for (let i = 0; i < lists.length; i++) {
            const result = await this.uploadFilePromise(lists[i])
            console.log('result',result);
            if (result != '') {
                let item = this[`fileList${event.name}`][fileListLen]
                this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
                    status: 'success',
                    message: '',
                    url: result
                }))
                fileListLen++
            }else{
                toastFunc('上传失败，请删除重试')
                this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign({}, {
                    status: 'fail',
                    message: '',
                    url: ''
                }))
            }
        }
    },
    uploadFilePromise(file) {
        return new Promise((resolve, reject) => {
            let a = uni.uploadFile({
                url: env.BASEURL + '/open/upload/uploadFile', // 仅为示例，非真实的接口地址
                filePath: file.url,
                name: 'file',
                success: (res) => {
                    const fileData = JSON.parse(res.data)
                    if (fileData.code == 500) {
                        resolve('')
                    }else{
                        const fileData = JSON.parse(res.data)
                        resolve(fileData.data.fileUrl)
                    }
                }
            });
        })
    },
    

}
}
</script>

<style lang="scss">
.bg{
    width: 750rpx;
    height: auto;
    border-radius: 0rpx 0rpx 0rpx 0rpx;

    display: flex;
    flex-direction: column;
    align-items: center;

    background: #f6f6f6;
}
.scrollview{
    width: 100vw;
    height: calc(100vh - 120rpx);
}
.formItemTitle{
    margin: 20rpx 0 20rpx 30rpx;
}
.btnbox{
    display: flex;
    position: fixed;
    bottom: 20rpx;
}
.u-form-item{
    background-color: #fff;
}
/deep/.u-form-item__body__left__content{
    padding-left: 30rpx;
}
/deep/.u-form-item__body__right{
    padding-right: 30rpx;
}
/deep/.u-form-item__body{
    padding: 30rpx 0;
}
.selectInput{
    display: flex;
    flex-direction: row;
    align-items: center;
}
.formItem {
    background: #fff;
}
.btn{
    width: 340rpx;
    height: 80rpx;
    background: #ffffff;
    border: 1rpx solid #dddddd;
    border-radius: 64rpx 64rpx 64rpx 64rpx;
    opacity: 1;

    font-size: 28rpx;
    font-weight: 500;
    color: #46A6FF;
    line-height: 80rpx;
    text-align: center;
}
.btn2{
    width: 650rpx;
    height: 80rpx;
    background: #46A6FF;
    border-radius: 64rpx 64rpx 64rpx 64rpx;
    opacity: 1;

    font-size: 28rpx;
    font-weight: 500;
    color: #FFFFFF;
    line-height: 80rpx;
    text-align: center;
    margin-left: 10rpx;
}
.margin20{
    margin-top: 20rpx;
}
.popupView{
    height: 430rpx;
    display: flex;
    padding-top: 100rpx;
    flex-direction: column;
    align-items: center;
}
.popupImg{
    width: 650rpx;
    height: 400rpx;
    background: #f6f6f6;
    border-radius: 16rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}
.popupViewText{
    width: 600rpx;
    height: 120rpx;
    font-size: 28rpx;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: 400;
    text-align: left;
    color: #999999;
    margin: 0 auto;
}
.btnflex{
    padding: 24rpx;
}
</style>
    