<template>
    <div class="info">
        <el-form :model="enforceHandbook" ref="ruleForm" label-width="150px" class="custom-form">
            <el-form-item label="检查类别">
                <div class="value">{{ enforceHandbook.enforce_class }}</div>
            </el-form-item>
            <el-form-item label="检查项">
                <div class="value">{{ enforceHandbook.enforce_item }}</div>
            </el-form-item>
            <el-form-item label="检查流程及方法" prop="enforce_method">
                <el-col :span="12">
                    <el-input type="textarea" maxlength="300"
                              show-word-limit rows="5" v-model="enforceHandbook.enforce_method"></el-input>
                </el-col>
            </el-form-item>
            <div v-for="(item, index) in problems" :key="index">
                <el-form-item :label="index === 0 ? '常见问题' : '常见问题' + (index + 1)" prop="enforce_method">
                    <el-row>
                        <el-col :span="12">
                            <el-input type="textarea" maxlength="300"
                                      show-word-limit rows="5" v-model="item.problem_desc"></el-input>
                        </el-col>
                        <el-col :span="6">
                            <div style="margin-left:10px;">
                                <el-button type="primary" v-if="problems.length !== 1"
                                           @click.native="deleteProlem(index)">删除
                                </el-button>
                                <el-button type="primary" v-if="index === problems.length - 1"
                                           @click.native="addProblem">新增
                                </el-button>
                            </div>
                        </el-col>
                    </el-row>
                    <el-row>
                        <div style="margin-top: 20px">
                            <el-upload
                                    class="upload-demo"
                                    list-type="picture-card"
                                    ref="upload"
                                    name="fileBinary"
                                    :headers="uploadHeaders"
                                    :data="uploadData"
                                    multiple
                                    with-credentials
                                    :action="fileUploadUrl"
                                    :on-remove="(file, fileList) => {
                      return handleFileRemove(file, fileList, index)
                  }"
                                    :on-success="(res, file, fileList) => {
                      return handleFileSuccess(res, file, fileList, index)
                  }"
                                    :on-preview="handlePictureCardPreview"
                                    :before-upload="beforeUploadFile"
                                    :file-list="item.fileList">
                                <i class="el-icon-plus"></i>
                            </el-upload>
                        </div>
                        <div slot="tip" class="el-upload__tip">支持文件格式：.jpeg .png .jpg ，单个文件不能超过500kb</div>
                    </el-row>
                </el-form-item>
            </div>
            <el-form-item label="设置要求" prop="enforce_method">
                <vue-editor v-model="enforceHandbook.setting_expect"/>
            </el-form-item>
            <el-form-item>
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="handleCommit">提交</el-button>
            </el-form-item>
        </el-form>
        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>

<script>
    import {updateEnforceHandBook, getEnforceHandbook} from '@/api/book'
    import {getTemplateDetail, updateTemplateDetail, addTemplateDetail} from '@/api/check'
    import {VueEditor} from 'vue2-editor'
    import {auth} from '@/utils/auth'
    import request from '@/utils/request'
    import { fileMixin } from '@/mixin/fileMixin'

    export default {
        components: {
            VueEditor
        },
        mixins: [fileMixin],
        data() {
            return {
                enforceHandbook: {
                    problems: [],
                    enforce_class: '其他',
                    enforce_item: ''
                },
                problems: [{
                    problem_desc: '',
                    fileList: []
                }],
                fileList: [],
                uploadData: {
                    fileName: ''
                },
                uploadHeaders: {
                    token: auth.getToken()
                },
                dialogImageUrl: '',
                dialogVisible: false
            }
        },
        computed: {
            resourceId() {
                return this.$route.query.id
            },
            enforceItem() {
                return this.$route.query.enforce_item
            }
        },
        mounted() {
            //  this.initDatas()
            this.enforceHandbook.enforce_item = this.enforceItem;
        },
        methods: {
            initDatas() {
                if (this.resourceId) {
                    getTemplateDetail(this.resourceId).then((res) => {
                        this.enforceHandbook = res
                        if (this.enforceHandbook.problems &&
                            this.enforceHandbook.problems.length !== 0) {
                            // this.problems = this.enforceHandbook.problems
                            this.getProblemFiles(this.enforceHandbook.problems)
                        }
                    })
                }
            },
            deleteProlem(index) {
                this.problems.splice(index, 1)
            },
            addProblem() {
                this.problems.push({
                    problem_desc: '',

                })
            },
            getProblemFiles(ps) {
                for (let k = 0; k < ps.length; k++) {
                    let item = ps[k];
                    if (!item.problem_images) {
                        return;
                    }

                    let arr = []
                    let imgs = item.problem_images.split(',').map(item => {
                        arr.push({url: `/v2/api/file/` + item, id: item})
                    })
                    item.fileList = arr
                }
                this.problems = ps
            },
            handlePreview(file) {
                console.log(file)
            },
            checkOrgLeaf(arr) {
                if (arr && arr.length > 0) {
                    const vm = this
                    arr.map(item => {
                        if (!item.children || item.children.length === 0) {
                            item.children = undefined
                        } else {
                            vm.checkOrgLeaf(item.children)
                        }
                    })
                }
            },
            handlePlace(data) {
                if (data) {
                    this.info.enforce_obj_address = data.address
                    this.info.longitude = data.lon
                    this.info.latitude = data.lat
                    this.info.coor = `${data.lon},${data.lat}`
                }
                this.showMap = false
            },
            changeCreditCode() {
                if (this.info.credit_code) {
                    this.info.credit_code = this.info.credit_code.toUpperCase()
                }
            },
            handleBook(data) {
                this.info.enforce_template_id = data.id
                this.info.enforce_template_name = data.handbook_name
                this.showBook = false
            },
            beforeUploadFile(file) {
                if (!/^image\/(jpeg|png|jpg)$/.test(file.type)) {
                    this.$message.warning(`上传图片格式不对[${file.name}]`)
                    return false
                }
                if (file.size / 1024 / 1024 > 10) {
                    this.$message.warning(`文件大小不能超过10M[${file.name}]`)
                    return false
                }
                this.uploadData.fileName = file.name
                return true
            },

            handleFileRemove(file, fileList, index) {
                this.handleUploadFiles(fileList, index)
            },
            handleFileSuccess(res, file, fileList, index) {
                console.log(index)
                this.handleUploadFiles(fileList, index)
            },
            getMappingValueArrayOfKey(array, keyName) {
                if (Object.prototype.toString.call(array) == '[object Array]') {
                    return array.map((item, index) => {
                        return item[keyName]
                    })
                }
                return 'null（参数一应为对象数组）';//不是数组
            },
            handleUploadFiles(fileList, index) {
                const res = []
                fileList.map(item => {
                    if (item.response && item.response.id) {
                        res.push(item.response.id)
                    } else if (item.id) {
                        res.push(item.id)
                    }
                })

                this.problems[index].problem_images = res.join(',')
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url
                this.dialogVisible = true
            },

            handleCancel() {
                this.$router.back()
            },
            handleCommit() {
                const vm = this
                // const enforceHandbook = Object.assign({}, this.enforceHandbook)
                const enforceHandbook = this.enforceHandbook
                this.problems.map((item, index, arr) => {
                    if (!item.problem_desc) {
                        enforceHandbook.problems.splice(index, 1)
                    }
                })
                enforceHandbook.problems = this.problems
                addTemplateDetail(this.resourceId, enforceHandbook).then(res => {
                    console.log(res)
                    vm.$message.success('修改成功')
                    vm.handleCancel()
                })
            },
            resetForm() {
                this.$refs['ruleForm'].resetFields()
            }
        },
    }
</script>

<style lang="scss" scoped>

    .info {
        display: flex;
        flex-direction: column;
        padding: 16px 16px 0;
        background-color: #FFFFFF;
        border-radius: 10px;
    }

    .label {
        text-align: right;
        border: none;
    }

    .value {
        text-align: left;
    }
</style>