<template>
    <div>
        <en-table-layout :tableData="tableData.records" :loading="loading">
            <div slot="toolbar" class="inner-toolbar">
                <div class="toolbar-btns">
                    <el-button size="mini" type="primary" v-if="checkPermission(['createStore:add'])"
                        @click="handleAdd">添加</el-button>
                </div>
                <div class="toolbar-search">
                    <en-table-search @search="handleSearchBranch" placeholder="请输入门店名称">
                    </en-table-search>
                </div>
            </div>

            <template slot="table-columns">
                <el-table-column prop="store_name" label="门店名称" />
                <el-table-column prop="contact_name" label="联系人" />
                <el-table-column prop="mobile" label="手机号" />
                <el-table-column prop="address" label="门店地址">
                    <template slot-scope="{ row }">
                        {{ row.province_name + row.city_name + row.area_name + row.address }}
                    </template>
                </el-table-column>
                <el-table-column prop="ss_status" label="闪送">
                    <template slot-scope="{ row }">{{ staType(row.ss_status) }}</template>
                </el-table-column>
                <el-table-column prop="dd_status" label="达达">
                    <template slot-scope="{ row }">{{ staType(row.dd_status) }}</template>
                </el-table-column>
                <el-table-column prop="fn_status" label="蜂鸟">
                    <template slot-scope="{ row }">{{ staType(row.fn_status) }}</template>
                </el-table-column>
                <el-table-column prop="mt_status" label="美团">
                    <template slot-scope="{ row }">{{ staType(row.mt_status) }}</template>
                </el-table-column>
                <el-table-column label="操作" width="300">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" @click="handleEdit(scope.row)"
                            v-if="checkPermission(['updateStore:update'])">编辑</el-button>
                        <el-button size="mini" v-if="checkPermission(['selectAudit:query'])"
                            @click="synchronization(scope.row)">同步
                        </el-button>
                        <!-- <el-button size="mini" type="danger" v-if="checkPermission(['store:delete'])"
                            @click="handleDelete(scope.row.id)">删除
                        </el-button> -->
                    </template>
                </el-table-column>
            </template>

            <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
                @current-change="handlePageCurrentChange" :current-page="tableData.page" :page-sizes="[10, 20, 50, 100]"
                :page-size="tableData.size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.total">
            </el-pagination>
        </en-table-layout>
        <el-dialog :title="storeForm.id ? '添加门店' : '编辑门店'" :visible.sync="dialogVisible" :close-on-click-modal="false"
            width="65%" :close-on-press-escape="false" @click="closeStore">
            <el-form :model="storeForm" ref="storeForm" :rules="storeFormRules" label-width="135px">
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="门店名称" prop="store_name">
                            <el-input v-model="storeForm.store_name" :disabled="disType" placeholder="请填完门店名称"
                                :maxlength="20"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="平台门店编码" prop="store_code">
                            <el-input v-model="storeForm.store_code" :maxlength="20" :disabled="disType"
                                placeholder="请填写平台门店编码"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="社会统一信用代码" prop="credit_code">
                            <el-input v-model="storeForm.credit_code" placeholder="请填写社会统一信用代码"
                                :maxlength="20"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="门店物品类型" prop="store_goods_type">
                            <el-select v-model="storeForm.store_goods_type" placeholder="请选择门店物品类型">
                                <el-option v-for="item in goodsList" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                            <!--  goodsList <el-input v-model="storeForm.store_goods_type" placeholder="请填写门店物品类型" :maxlength="20"></el-input> -->
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="门店联系人姓名" prop="contact_name">
                            <el-input v-model="storeForm.contact_name" placeholder="请填写门店联系人姓名"
                                :maxlength="20"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="联系人电话" prop="mobile">
                            <el-input v-model="storeForm.mobile" placeholder="请填写联系人电话" :maxlength="20"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="身份证姓名" prop="id_card_name">
                            <el-input v-model="storeForm.id_card_name" placeholder="请填写身份证姓名"
                                :maxlength="20"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="身份证号码" prop="id_card">
                            <el-input v-model="storeForm.id_card" placeholder="请填写身份证号码" :maxlength="20"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="20">
                        <el-form-item label="门店地址" prop="id_card">
                            <el-cascader size="small" :options="options" clearable v-model="selectedOptions"
                                @change="handleChange">
                            </el-cascader>
                            <el-input v-model="storeForm.address" placeholder="请输入门店详细地址"
                                style="width: 30%;"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="身份证正面照片" prop="id_card_front">
                            <el-upload class="site-logo" :action="MixinUploadApi" :show-file-list="false"
                                :on-success="(res) => handleUploadSuccess(res, 'id_card_front')" :multiple="false">
                                <img v-if="storeForm.id_card_front" :src="storeForm.id_card_front"
                                    class="site-logo-img">
                                <i v-else class="el-icon-plus logo-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="身份证反面照片" prop="id_card_back">
                            <el-upload class="site-logo" :action="MixinUploadApi" :show-file-list="false"
                                :on-success="(res) => handleUploadSuccess(res, 'id_card_back')" :multiple="false">
                                <img v-if="storeForm.id_card_back" :src="storeForm.id_card_back" class="site-logo-img">
                                <i v-else class="el-icon-plus logo-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="门店拥有人手持身份证或营业执照图片" prop="handheld_licence_pic">
                            <el-upload class="site-logo" :action="MixinUploadApi" :show-file-list="false"
                                :on-success="(res) => handleUploadSuccess(res, 'handheld_licence_pic')"
                                :multiple="false">
                                <img v-if="storeForm.handheld_licence_pic" :src="storeForm.handheld_licence_pic"
                                    class="site-logo-img">
                                <i v-else class="el-icon-plus logo-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="门店照图片" prop="shop_picture">
                            <el-upload class="site-logo" :action="MixinUploadApi" :show-file-list="false"
                                :on-success="(res) => handleUploadSuccess(res, 'shop_picture')" :multiple="false">
                                <img v-if="storeForm.shop_picture" :src="storeForm.shop_picture" class="site-logo-img">
                                <i v-else class="el-icon-plus logo-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="营业执照图片" prop="license">
                            <el-upload class="site-logo" :action="MixinUploadApi" :show-file-list="false"
                                :on-success="(res) => handleUploadSuccess(res, 'license')" :multiple="false">
                                <img v-if="storeForm.license" :src="storeForm.license" class="site-logo-img">
                                <i v-else class="el-icon-plus logo-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeStore">取 消</el-button>
                <el-button type="primary" @click="submitForm()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import * as API_Branch from '@/api/basicSetting'
import {
    provinceAndCityData,
    pcTextArr,
    regionData,
    pcaTextArr,
    codeToText,
} from "element-china-area-data";
export default {
    name: 'store',
    data() {
        return {
            options: regionData,
            selectedOptions: [],

            // 列表loading状态
            loading: false,
            // 列表参数
            params: {
                page_no: 1,
                page_size: 10,
                shop_name: ''
            },
            advancedForm: {
                link_name: '',
                link_phone: ''
            },
            // 列表数据
            tableData: '',
            dialogVisible: false, // 添加弹窗
            storeForm: {}, // 添加表单
            //表单校验
            storeFormRules: {
                store_name: [this.MixinRequired('请填写门店名称！')],
                store_code: [
                    this.MixinRequired('请填写平台门店编码！'),
                    {
                        validator: (rule, value, callback) => {
                            if (/^[A-Za-z0-9]+$/.test(value)) {
                                callback();
                            } else {
                                callback(new Error('门店编码只能包含字母和数字！'));
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                credit_code: [this.MixinRequired('请填写社会统一信用代码！'),
                {
                    validator: (rule, value, callback) => {
                        if (/^[A-Za-z0-9]+$/.test(value)) {
                            callback();
                        } else {
                            callback(new Error('门店编码只能包含字母和数字！'));
                        }
                    },
                    trigger: 'blur'
                }],
                store_goods_type: [this.MixinRequired('请填写名店名称！')],
                contact_name: [this.MixinRequired('请填写门店联系人姓名！')],
                mobile: [this.MixinRequired('请填写联系人电话！'),
                {
                    validator: (rule, value, callback) => {
                        const mobileRegex = /^1[3-9]\d{9}$/; // 中国大陆手机号正则表达式
                        if (!mobileRegex.test(value)) {
                            callback(new Error("手机号码格式有误！"));
                        } else {
                            callback();
                        }
                    },
                    trigger: ["change", "blur"],
                },
                ],
                id_card_name: [this.MixinRequired('请填写身份证姓名！')],
                id_card: [this.MixinRequired('请填写身份证号码！')],
                id_card_front: [this.MixinRequired('请上传身份证正面照片！')],
                id_card_back: [this.MixinRequired('请上传身份证反面照片！')],
                handheld_licence_pic: [this.MixinRequired('请上传门店拥有人手持身份证或营业执照图片！')],
                shop_picture: [this.MixinRequired('请上传门店照图片！')],
                license: [this.MixinRequired('请上传营业执照图片！')],
            },
            typeList: [
                {
                    label: '未审核',
                    id: 1,
                },
                {
                    label: '创建失败',
                    id: 3,
                },
                {
                    label: '已开启',
                    id: 4,
                },
                {
                    label: '未认证',
                    id: 5,
                }
            ],
            goodsList: [
                {
                    label: '文件',
                    value: '1'
                },
                {
                    label: '电子产品',
                    value: '2'
                },
                {
                    label: '蛋糕',
                    value: '3'
                },
                {
                    label: '快餐',
                    value: '4'
                },
                {
                    label: '鲜花绿植',
                    value: '5'
                },


                {
                    label: '海鲜水产',
                    value: '6'
                },
                {
                    label: '汽车配件',
                    value: '7'
                },
                {
                    label: '宠物',
                    value: '8'
                },
                {
                    label: '母婴',
                    value: '9'
                },
                {
                    label: '医疗健康',
                    value: '10'
                },

                {
                    label: '教育',
                    value: '11'
                },
                {
                    label: '服装',
                    value: '12'
                },
                {
                    label: '百货',
                    value: '13'
                },

                {
                    label: '水果',
                    value: '14'
                },
                {
                    label: '图文广告',
                    value: '15'
                },
                {
                    label: '其他',
                    value: '99'
                },
            ],
            disType: false
        }
    },
    watch: {
        '$route': {
            immediate: true,
            handler(newVal) {
                if (newVal.name !== 'kdnStore') return
                this.params.franchise_id = newVal.query.franchise_id
                this.GET_BranchList()
            }
        }
    },
    methods: {
        //关闭
        closeStore() {
            this.disType = false
            this.dialogVisible = false
            this.storeForm = {}
        },
        //店铺创建状态
        staType(value) {
            const type = this.typeList.find(type => type.id === value);
            return type ? type.label : '未知类型';
        },
        //同步状态
        synchronization(row) {
            API_Branch.selectAudit(row).then(res => {
                this.GET_BranchList()
            })
        },
        //图片上传
        handleUploadSuccess(res, key) {
            if (res.url) {
                this.$set(this.storeForm, key, res.url);
            } else {
                this.$message.error('图片上传失败，请重新上传。');
            }
        },
        handleChange(value) {
            this.storeForm.province_name =
                codeToText[this.selectedOptions[0]];
            this.storeForm.city_name =
                codeToText[this.selectedOptions[1]];
            this.storeForm.area_name =
                codeToText[this.selectedOptions[2]];
            /*            console.log(Array.isArray(this.storeForm.province_city_area)); 
                       console.log(this.storeForm.province_city_area);  */
            this.storeForm.province_city_area = value.join(",");
            //打印区域码所对应的属性值即中文地址
        },
        /** 分页大小发生改变 */
        handlePageSizeChange(size) {
            this.params.page_size = size
            this.GET_BranchList()
        },

        /** 分页页数发生改变 */
        handlePageCurrentChange(page) {
            this.params.page_no = page
            this.GET_BranchList()
        },

        /** 搜索 */
        handleSearchBranch(keyword) {
            this.params.page_no = 1
            this.params.store_name = keyword
            this.GET_BranchList()
        },

        /** 添加 */
        handleAdd() {
            this.disType = false
            this.dialogVisible = true
            this.storeForm = {}
        },

        /** 编辑 */
        handleEdit(row) {
            this.disType = true
            this.dialogVisible = true
            this.selectedOptions = row.province_city_area.split(",")
            this.storeForm = row
        },

        /** 删除 */
        handleDelete(id) {
            let msg = '确认删除当前门店？'
            this.$confirm(msg, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                API_Branch.deleteStore(id).then(res => {
                    this.$message.success('删除成功！')
                    this.GET_BranchList()
                })
            })
        },

        /** 获取门店列表 */
        async GET_BranchList(advanced) {
            let params = this.MixinClone(this.params)
            if (advanced) {
                params = { ...params, ...this.advancedForm }
            }
            this.loading = true
            try {
                this.tableData = await API_Branch.getList(params)
            } finally {
                this.loading = false
            }
        },

        /** 提交表单 */
        submitForm() {
            this.$refs['storeForm'].validate(valid => {
                if (valid) {
                    if (this.storeForm.city_name === '市辖区') {
                        this.storeForm.city_name = this.storeForm.province_name;
                    }
                    if (this.storeForm.id) {
                        API_Branch.updateStore(this.storeForm).then(res => {
                            this.$message.success('修改成功！')
                            this.dialogVisible = false
                            this.storeForm = {}
                            this.disType = false
                            this.GET_BranchList()
                        })
                    } else {
                        API_Branch.addCreateStore(this.storeForm).then(res => {
                            this.$message.success('添加成功！')
                            this.dialogVisible = false
                            this.storeForm = {}
                            this.GET_BranchList()
                        })
                    }
                } else {
                    this.$message.error('请检查表单！')
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.toolbar-search {
    display: flex;

    .item-search {
        display: flex;
        align-items: center;

        &+.item-search {
            margin-left: 10px;
        }

        >span {
            flex-shrink: 0;
            font-size: 12px;
            color: #666666;
        }
    }

    .search-btn {
        margin-left: 10px;
    }
}

/deep/ .site-logo .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    &:hover {
        border-color: #409EFF;
    }
}

.logo-uploader-icon {
    font-size: 20px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
}

.site-logo-img {
    width: 120px;
    height: 120px;
    display: block;
}
</style>