<template>
    <div class="app-container">
        <el-form ref="form" :model="localFormState" :rules="rules" label-width="100px">
            <div class="info-header">
                <p class="info-title">标准识别码</p>
            </div>
            <el-divider class="mini-divider-table" />
            <el-row type="flex">
                <el-col :span="12">
                    <el-form-item label="ISBN码" prop="isbn">
                        <el-input v-model.trim="localFormState.isbn" maxlength="13" class="paddingR10"
                            @input="localFormState.isbn = localFormState.isbn.replace(/^(0+)|[^\d]+/g, '')"
                            show-word-limit clearable placeholder="请输入ISBN编码" :disabled="isbnStatus" />
                        <el-button size="mini" v-if="!isbnStatus" style="display: inline-block; margin-left: 12px"
                            type="primary" :loading="loadingBtn" @click="identifyISBN">识别</el-button>
                        <el-button size="mini" v-else style="display: inline-block; margin-left: 12px" type="warning"
                            @click="handleChangeIbsnStatus">修改</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
            <div class="info-header">
                <p class="info-title">基本信息</p>
            </div>
            <el-divider class="mini-divider-table" />
            <el-row type="flex">
                <el-col :span="12">
                    <el-form-item label="中文名称" prop="chineseName">
                        <el-input v-model="localFormState.chineseName" maxlength="20" class="paddingR10" show-word-limit
                            clearable placeholder="请输入中文名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="英文名称">
                        <el-input v-model="localFormState.englishName" maxlength="100" class="paddingR100"
                            show-word-limit clearable placeholder="请输入英文名称" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row type="flex">
                <el-col :span="12">
                    <el-form-item label="封面" prop="coverImg">
                        <upload-book-img :file-list.sync="localFormState.coverImg" :limit="1"
                            :form-state.sync="localFormState" placeholder="建议上传3:4图片，10M以内" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="封底">
                        <upload-book-img :file-list.sync="localFormState.backCoverImg" :limit="1"
                            :form-state.sync="localFormState" placeholder="建议上传3:4图片，10M以内" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="插页">
                <upload-book-img :file-list.sync="localFormState.insertPageImg" :form-state.sync="localFormState"
                    placeholder="最多上传5张，建议上传3:4图片，10M以内" :limit="5" />
            </el-form-item>
            <el-row type="flex">
                <el-col :span="12">
                    <el-form-item label="文字作者" prop="author">
                        <el-input v-model="localFormState.author" maxlength="100" class="paddingR100" show-word-limit
                            clearable placeholder="请输入作者名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="图画作者">
                        <el-input v-model="localFormState.pictureAuthor" maxlength="100" class="paddingR100"
                            show-word-limit clearable placeholder="请输入作者名称" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row type="flex">
                <el-col :span="12">
                    <el-form-item label="译者">
                        <el-input v-model="localFormState.translator" maxlength="10" class="paddingR10" show-word-limit
                            clearable placeholder="请输入译者名称" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row type="flex">
                <el-col :span="12">
                    <el-form-item label="出版社">
                        <publishers-dialog ref="publishersDialog" v-model="localFormState.publisherId"
                            placeholder="请选择出版社" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="出版年月">
                        <el-date-picker v-model="localFormState.publishDate" type="month" placeholder="选择年月"
                            value-format="yyyy-MM" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row type="flex">
                <el-col :span="12">
                    <el-form-item label="开本">
                        <check-box v-model="localFormState.formt" :data="dict.type['book_type_format']" />
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="localFormState.formt == 3">
                    <el-form-item label="其他尺寸">
                        <el-input v-model.trim="localFormState.formtContent" clearable
                            placeholder="单位mm或XX开，例如160*320或27开" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row type="flex">
                <el-col :span="12">
                    <el-form-item label="套装">
                        <check-box v-model="localFormState.series" :data="dict.type['book_type_series']"
                            @change="handleChangeSeries" />
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="localFormState.series == 1">
                    <el-form-item label="套装名称" prop='seriesId'>
                        <series-dialog ref="seriesDialog" v-model="localFormState.seriesId" placeholder="请选择套装" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="包装">
                <check-box v-model="localFormState.binding" :data="dict.type['book_type_package']" />
            </el-form-item>
            <el-form-item label="图书介绍">
                <editor v-model="localFormState.summary" :min-height="192" :style="containerStyle" />
            </el-form-item>
            <el-form-item label="配套附件">
                <template v-if="localFormState.attachmentList && localFormState.attachmentList.length > 0">
                    <el-tag v-for="(item, index) in localFormState.attachmentList" :key="item.id"
                        class="mr10 mb5 tag-no-border" closable @close="handleCloseAttachFile(item, index)">{{
            item.fileFullName }}</el-tag>
                </template>
                <el-button class="tag-button" type="primary" plain size="small"
                    @click="$refs.attachDialogRef.handleOpen([], [].concat(localFormState.attachmentList))">上传附件</el-button>
            </el-form-item>
            <div class="info-header">
                <p class="info-title">基础属性</p>
            </div>
            <el-divider class="mini-divider-table" />
            <el-form-item label="领域">
                <check-book-area v-model="localFormState.fieldNameList" />
            </el-form-item>
            <el-form-item label="班龄段">
                <check-class-age v-model="localFormState.classAgeNameList" /></el-form-item>
            <el-form-item label="标签库">
                <template v-if="localFormState.checkedTags && localFormState.checkedTags.length > 0">
                    <el-tag v-for="(item, index) in localFormState.checkedTags" :key="item.userId"
                        class="mr10 mb5 tag-no-border" closable @close="handleCloseCheckedTags(item, index)">{{
            item.labelDesc
        }}</el-tag>
                </template>
                <el-button class="tag-button" type="primary" plain size="small"
                    @click="$refs.tagDialogRef.handleOpen(localFormState.checkedTags)">添加标签</el-button></el-form-item>
            <el-form-item label="核心经验">
                <common-dialog v-model="localFormState.localData1" title="核心经验" button-name="选择核心经验" label-key="id"
                    :tree-data="treeData1" :placeholder="placeholder1" children="profileCoreExperienceList"
                    label="detailDesc" title-class="content-title" require-label="require-label"
                    @ok="(val) => localFormState.localData1 = val" />
            </el-form-item>
            <el-form-item label="3-6指南">
                <common-dialog v-model="localFormState.localData2" title="3-6指南" button-name="选择3-6指南条目" label-key="id"
                    :tree-data="treeData2" :placeholder="placeholder2" children="children" label="name"
                    require-label="require-label" @ok="(val) => localFormState.localData2 = val" />
            </el-form-item>
            <div class="info-header">
                <p class="info-title">状态</p>
            </div>
            <el-divider class="mini-divider-table" />
            <el-form-item label="状态" prop="status">
                <check-box v-model="localFormState.status" :data="options.toySysStatus" />
            </el-form-item>
        </el-form>
        <book-isbn-info-dialog ref="isbnDialogRef" @ok="handleCover" />
        <select-tag-dialog ref="tagDialogRef" @checked="(tags) => (localFormState.checkedTags = tags)" />
        <upload-dialog ref="attachDialogRef" @ok="handleAttach" />
    </div>
</template>


<script>
import options from "@/utils/dict/options";
import DictType from "@/utils/dict/DictType";
import BookIsbnInfoDialog from "@/views/book/info/modules/BookIsbnInfoDialog.vue";
import { IBSNQuery } from "@/api/book/info";
import { SelectTagDialog } from "@/views/profile/components";
import { UploadDialog, CheckBookArea, CheckBox } from "@/views/book/components";
import commonDialog from "@/views/book/info/modules/commonDialog.vue";
import { fetchExperienceTreeList, fetchGuideTreeList, } from '@/api/profile/case'
import { CheckClassAge, } from "@/components/CheckBox";
import { removeFile } from '@/api/file'
import UploadBookImg from '@/components/Upload/UploadBookImg.vue'
import PublishersDialog from '@/views/book/info/modules/PublishersDialog.vue';
import SeriesDialog from "@/views/book/info/modules/SeriesDialog.vue";
import { deepClone } from '@/utils/index'
export default {
    name: "EditBasic",
    dicts: ["book_type_series", 'book_type_package', 'book_type_format'],
    components: {
        BookIsbnInfoDialog,
        SelectTagDialog,
        UploadDialog,
        commonDialog,
        CheckClassAge,
        CheckBox,
        CheckBookArea,
        UploadBookImg,
        PublishersDialog,
        SeriesDialog,
    },
    data() {
        const ArrayHasContent = (voteRule, value, callback) => {
            if (value.length > 0) {
                callback()
            } else {
                callback(new Error(`请上传封面`))
            }
        }
        const chineseNameOnTrim = (voteRule, value, callback) => {
            if (!!value) {
                const valueTrim = value.trim()
                if (!!valueTrim) {
                    callback()
                } else {
                    callback(new Error(`请输入图书中文名称`))
                }
            } else {
                callback(new Error(`请输入图书中文名称`))
            }
        }
        return {
            options,
            DictType,
            loading: false,
            loadingBtn: false,
            rules: {
                isbn: [
                    {
                        required: true,
                        min: 13,
                        message: "ISBN码不足13位",
                        trigger: ['change', 'blur'],
                    },
                    {
                        required: true,
                        pattern: /^(978|979)\d{10}$/,
                        message: "ISBN码格式错误",
                        trigger: ['change', 'blur'],
                    },
                ],
                chineseName: [

                    { validator: chineseNameOnTrim, message: '', trigger: ['change', 'blur'] },
                    {
                        required: true,
                        max: 20,
                        message: "图书中文名称不能超过20个字符",
                        trigger: ['change', 'blur'],
                    },
                ],
                author: [
                    {
                        required: false,
                        max: 100,
                        message: "文字作者不能超过100个字符",
                        trigger: ['change', 'blur'],
                    },
                ],
                coverImg: [
                    {
                        required: true,
                        validator: ArrayHasContent,
                        trigger: ['change', 'blur'],
                    },
                ],
                seriesId: [
                    {
                        required: true,
                        message: "请选择套装",
                        trigger: ['change', 'blur'],
                    },
                ],
                status: [
                    {
                        required: true,
                        message: "请选择状态",
                        trigger: ['change', 'blur'],
                    },
                ],
            },
            isbnStatus: false,
            labelFlagFILE: false,
            labelFlagExperience: false,
            labelFlagGuide: false,
            treeData1: [],
            treeData2: [],
            placeholder1: {
                'dimension': '请选择维度',
                'mode': '请选择模块',
                'points': '请选择观察要点'
            },
            placeholder2: {
                'dimension': '请选择领域',
                'mode': '请选择类别',
                'points': '请选择目标',
                'age': '请选择年龄段'
            },
        };
    },
    props: {
        formState: {
            type: Object,
            default: () => {
                return {};
            },
        },
        containerStyle: {
            type: Object,
            default: () => { }
        },
        isEdit: {
            type: Boolean,
            default: false,
        }
    },
    watch: {
        isEdit: {
            handler(val) {
                this.isbnStatus = val;
            },
            immediate: true,
        },
        //监听
        'localFormState.coverImg': {
            handler(val) {
                if (val.length > 0) {
                    this.$refs.form.validateField('coverImg')
                }
            },
            immediate: true,
        }
    },
    computed: {
        localFormState() {
            return this.formState;
        },
    },
    mounted() {
        this.fetchExperienceTreeList()
        this.fetchGuideTreeList()
        this.scrollToTop();
    },
    methods: {
        scrollToTop() {
            const elScrollbar = document.querySelector('.main-container .el-scrollbar__wrap')
            if (elScrollbar) {
                elScrollbar.scrollTop = 0
            }
        },
        async identifyISBN() {
            const a = await this.cusTomValid("isbn");
            if (!!a) {
                return false;
            }
            this.loadingBtn = true;
            IBSNQuery(this.localFormState.isbn).then((res) => {
                if (!!res.data) {
                    this.$refs.isbnDialogRef.handleOpen(res.data, this.localFormState);
                } else {
                    this.$message.error("未查询到该ISBN编码");
                }
                this.loadingBtn = false;
            }).catch(() => {
                this.loadingBtn = false;
            });
        },
        handleChangeIbsnStatus() {
            this.$confirm('改动ISBN码，会导致图书信息不匹配，需要您修改图书信息并核对', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                this.isbnStatus = !this.isbnStatus
            }).catch(() => {
            })
        },
        //公共校验方法
        cusTomValid(name) {
            return new Promise((resolve, reject) => {
                this.$refs.form.validateField([name], (err) => {
                    resolve(err);
                });
            });
        },
        //其他部分
        fetchExperienceTreeList() {
            this.loading = true
            fetchExperienceTreeList().then(({ data }) => {
                this.treeData1 = data
            }).finally(() => {
                this.loading = false
            })
        },
        fetchGuideTreeList() {
            this.loading = true
            fetchGuideTreeList().then(({ data }) => {
                this.treeData2 = data
            }).finally(() => {
                this.loading = false
            })
        },
        handleAttach(fileList) {
            this.localFormState.attachmentList.push(...fileList)
        },
        handleCloseCheckedTags(item, index) {
            this.localFormState.checkedTags.splice(index, 1)
        },
        handleCloseAttachFile(file, index) {
            let fileList = [];
            if (Array.isArray(file)) {
                fileList = file;
            } else {
                fileList = [file]
            }
            removeFile(fileList).then()
            this.localFormState.attachmentList.splice(index, 1)
        },
        handleChangeSeries(val) {
            if (val != 1) {
                this.localFormState.seriesId = null
            }
        },
        handleCover(formData) {
            this.$refs.publishersDialog.getPublishingList();
            for (let key in formData) {
                this.localFormState[key] = formData[key];
            }
            this.isbnStatus = true;
            //重新拉列表
            this.$nextTick(() => {
                this.scrollToTop();
            })
        },
        onSubmit() {
            return new Promise((resolve, reject) => {
                Promise.all([this.$refs.form.validate()]).then(async (result) => {
                    const valid = result.every(v => v)
                    let values = {}
                    if (valid) {
                        values = Object.assign({}, deepClone(this.localFormState))
                        resolve({
                            valid,
                            values
                        })
                    }
                }).catch((error) => {
                    console.log(error)
                    reject(error)
                })
            })
        }
    },
};
</script>

<style scoped lang="scss">
.category-flex {
    display: flex;
}

.category-wrapper {
    ::v-deep .el-form-item {
        margin-right: 10px;
    }
}

::v-deep .category-options {
    width: 64px;
    text-align: center;

    &>span {
        height: 24px;

        .el-popover__reference-wrapper {
            width: 24px;
            height: 24px;

            &>i {
                margin: unset;
            }
        }
    }
}

.cover-image {
    width: 90px;
    height: 90px;
    border-radius: 4px;
}

.el-color-picker__icon,
.el-input,
.el-textarea {
    width: 70%;
}

::v-deep .paddingR10>.el-input__inner {
    padding-right: 70px;
}

::v-deep .paddingR100>.el-input__inner {
    padding-right: 76px;
}
</style>
