<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="60vw" @confirm="handleSubmit" @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="商户头像" prop="mer_avatar">
                            <material-picker v-model="formData.mer_avatar" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="商户名称" prop="mer_name">
                            <el-input v-model="formData.mer_name" clearable placeholder="请输入商户名称" :readonly="false" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="商户分类" prop="category_id">
                            <el-select class="flex-1" v-model="formData.category_id" clearable placeholder="请选择店铺类型">
                                <el-option v-for="(item, index) in dictData.mer_category_type" :key="index"
                                    :label="item.name" :value="parseInt(item.value)" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="店铺类型" prop="type_id">
                            <el-select class="flex-1" v-model="formData.type_id" clearable placeholder="请选择店铺类型">
                                <el-option v-for="(item, index) in dictData.merchat_type" :key="index" :label="item.name"
                                    :value="parseInt(item.value)" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="结算周期(天)" prop="settle_cycle">
                            <el-input v-model="formData.settle_cycle" clearable placeholder="请输入结算周期，单位天"
                                :readonly="false" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="利率" prop="interest_rate">
                            <el-input v-model="formData.interest_rate" clearable placeholder="请输入利率" :readonly="false" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="城市" prop="city_id">
                            <el-select class="flex-1" v-model="formData.city_id" clearable placeholder="请选择城市"
                                @change="getAreaList(formData.city_id)">
                                <el-option v-for="(item, index) in address.cityList" :key="index" :label="item.city_name"
                                    :value="parseInt(item.city_code)" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="区县" prop="area_id">
                            <el-select class="flex-1" v-model="formData.area_id" clearable placeholder="请选择城市"
                                @change="getTownList(formData.area_id)">
                                <el-option v-for="(item, index) in address.areaList" :key="index" :label="item.area_name"
                                    :value="parseInt(item.area_code)" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="镇街" prop="street_id">
                            <el-select class="flex-1" v-model="formData.street_id" clearable placeholder="请选择城市"
                                @change="getVilllageList(formData.street_id)">
                                <el-option v-for="(item, index) in address.townList" :key="index" :label="item.street_name"
                                    :value="parseInt(item.street_code)" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="村" prop="village_id">
                            <el-select class="flex-1" v-model="formData.village_id" clearable placeholder="请选择城市">
                                <el-option v-for="(item, index) in address.villlageList" :key="index"
                                    :label="item.village_name" :value="(item.village_code)" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="商户地址" prop="mer_address">
                            <el-input v-model="formData.mer_address" clearable placeholder="请输入商户地址" :readonly="false" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="商户是否禁用" prop="status">
                            <el-radio-group v-model="formData.status" placeholder="请选择商户是否禁用" :disabled="false">
                                <el-radio v-for="(item, index) in dictData.show_status" :key="index"
                                    :label="parseInt(item.value)">
                                    {{ item.name }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="提成比例" prop="commission_rate">
                            <el-input v-model="formData.commission_rate" type="number" clearable placeholder="请输入提成比例"
                                :readonly="false" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="商户手续费单独设置" prop="commission_switch" label-width="180px">
                            <el-radio-group v-model="formData.commission_switch" placeholder="请选择商户手续费单独设置"
                                :disabled="false">
                                <el-radio v-for="(item, index) in dictData.show_status" :key="index"
                                    :label="parseInt(item.value)">
                                    {{ item.name }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="经度" prop="long">
                            <el-input v-model="formData.long" clearable placeholder="请输入经度" :readonly="false" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="纬度" prop="lat">
                            <el-input v-model="formData.lat" clearable placeholder="请输入纬度" :readonly="false" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="店铺电话" prop="service_phone">
                            <el-input v-model="formData.service_phone" clearable placeholder="请输入店铺电话" :readonly="false" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="商户余额" prop="mer_money">
                            <el-input v-model="formData.mer_money" clearable placeholder="请输入商户余额" :readonly="false" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="商户备注" prop="mark">
                            <el-input v-model="formData.mark" clearable placeholder="请输入商户备注" type="textarea"
                                :readonly="false" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="银行卡转账信息" prop="financial_bank">
                            <el-input v-model="formData.financial_bank" clearable placeholder="请输入银行卡转账信息"
                                :readonly="false" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="微信转账信息" prop="financial_wechat">
                            <el-input v-model="formData.financial_wechat" clearable placeholder="请输入微信转账信息"
                                :readonly="false" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="支付宝转账信息" prop="financial_alipay">
                            <el-input v-model="formData.financial_alipay" clearable placeholder="请输入支付宝转账信息"
                                :readonly="false" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="默认使用类型" prop="financial_type">
                            <el-select class="flex-1" v-model="formData.financial_type" clearable placeholder="请选择默认使用类型">
                                <el-option v-for="(item, index) in dictData.financial_type" :key="index" :label="item.name"
                                    :value="parseInt(item.value)" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="标签" prop="sys_labels">
                            <el-tag class="mr-2" v-for="(item, index) in formData.sys_labels_arr" @close="delTags(index)"
                                :key="index" closable>
                                {{ item.name }}
                            </el-tag>
                            <el-button type="primary" @click="showDialog = true">添加标签</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <el-dialog v-model="showDialog" title="选择标签" width="70%">
                <dialogTable multipleChoice :config="goods_label" @customEvent="customEvent">
                </dialogTable>
            </el-dialog>
        </popup>
    </div>
</template>

<script lang="ts" setup name="supplierEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiSupplierAdd, apiSupplierEdit, apiSupplierDetail } from '@/api/supplier'
import { apicityLists, apiAreaLists, apiStreetLists, apiVillageLists } from "@/api/address"
import { goods_label } from "@/components/dialogTable/dialogTableConfig"
import type { PropType } from 'vue'


defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const showDialog = ref(false)

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑供应商表' : '新增供应商表'
})

// 表单数据
const formData = reactive({
    id: '',
    category_id: '',
    type_id: '',
    mer_name: '',
    settle_cycle: '',
    interest_rate: '',
    sys_labels: [],
    sys_labels_text: '',
    province_id: '510000',
    city_id: '',
    area_id: '',
    street_id: '',
    village_id: '',
    mer_address: '',
    mer_avatar: '',
    mark: '',
    status: '',
    commission_rate: '',
    commission_switch: '',
    long: '',
    lat: '',
    service_phone: '',
    mer_money: '',
    financial_bank: '',
    financial_wechat: '',
    financial_alipay: '',
    financial_type: '',
    sys_labels_arr: []
})

const customEvent = (e) => {
    e.forEach(item => {
        formData.sys_labels_arr.push(item)
    });
    formData.sys_labels_arr = Array.from(new Set(formData.sys_labels_arr.map(obj => JSON.stringify(obj)))).map(str => JSON.parse(str));
    showDialog.value = false
}


// 表单验证
const formRules = reactive<any>({
    category_id: [{
        required: true,
        message: '请输入商户分类 id',
        trigger: ['blur']
    }],
    mer_name: [{
        required: true,
        message: '请输入商户名称',
        trigger: ['blur']
    }],
    settle_cycle: [{
        required: true,
        message: '请输入结算周期，单位天',
        trigger: ['blur']
    }],
    interest_rate: [{
        required: true,
        message: '请输入利率',
        trigger: ['blur']
    }],
    mer_address: [{
        required: true,
        message: '请输入商户地址',
        trigger: ['blur']
    }],
    mark: [{
        required: true,
        message: '请输入商户备注',
        trigger: ['blur']
    }],
    status: [{
        required: true,
        message: '请选择商户是否禁用0锁定,1正常',
        trigger: ['blur']
    }],
    service_phone: [{
        required: true,
        message: '请输入店铺电话',
        trigger: ['blur']
    }],
    mer_money: [{
        required: true,
        message: '请输入商户余额',
        trigger: ['blur']
    }]
})

// 标签列表
const delTags = (index: number) => {
    formData.sys_labels_arr.splice(index, 1)
}


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    await getAreaList(formData.city_id, true)
    await getTownList(formData.area_id, true)
    getVilllageList(formData.street_id)
    if (data.financial_type == 0) {
        formData.financial_type = ''
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiSupplierDetail({
        id: row.id
    })
    setFormData(data)
}


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData, }
    data.sys_labels = data.sys_labels_arr.map(item => {
        return item.id
    }).join(',')
    mode.value == 'edit'
        ? await apiSupplierEdit(data)
        : await apiSupplierAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}
// 510000


// 地址
const address = reactive({
    cityList: [],
    areaList: [],
    townList: [],
    villlageList: []
})

const getCityList = async (province_code: number | String, isAsync: Boolean) => {
    if (!province_code) return;
    let res = await apicityLists({ province_code })
    address.cityList = res
    if (isAsync) {
        return Promise.resolve({
            msg: '获取成功'
        });
    }
}


const getAreaList = async (city_code: number | String, isAsync: Boolean) => {
    if (!city_code) return;
    let res = await apiAreaLists({ city_code })
    address.areaList = res
    if (isAsync) {
        return Promise.resolve({
            msg: '获取成功'
        });
    }
}


const getTownList = async (area_code: number | String, isAsync: Boolean) => {
    if (!area_code) return;
    let res = await apiStreetLists({ area_code })
    address.townList = res
    if (isAsync) {
        return Promise.resolve({
            msg: '获取成功'
        });
    }
}

const getVilllageList = async (street_code: number | String) => {
    if (!street_code) return;
    let res = await apiVillageLists({ street_code })
    address.villlageList = res
}
// 地址结束

getCityList(510000, false)


defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
