<template>
    <div class="mta-import">
        <el-dialog v-if="showDialogType===1"
                   :title="dialogTitleText"
                   center
                   :visible.sync="showDialog"
                   :requestData="requestData"
                   :show-close="true"
                   @close="dialogClose"
                   :modal-append-to-body="modalAppendToBody"
                   :close-on-click-modal="false"
                   class="response-middle-dialog">
            <div class="import-head">
                <div class="downloadTem" @click="downloadFun" style="cursor: pointer">
                    <div class="img-box">
                        <img :src="importDownImg" alt="">
                    </div>
                    <span>下载模版</span>
                </div>
                <div class="import-jt">
                    <span></span>
                </div>
                <div class="downloadTem">

                    <el-upload
                            class="upload-demo"
                            action="https://jsonplaceholder.typicode.com/posts/"
                            :show-file-list="false"
                            :http-request="importFun"
                    >
                        <div class="img-box">
                            <img :src="importImg" alt="">
                        </div>
                        <span>{{dataImportText}}</span>
                    </el-upload>
                </div>
            </div>
            <div class="drjg-box">
                <span>导入结果</span>
                <div>
                    <div class="successSpan">导入成功数据：<span class="color-p">{{listSuccess}}条</span></div>
                    <div  class="errorSpan">导入失败数据：<span style="color: #e51c23;">{{listError}}条</span></div>
                    <!-- <div>详细错误信息：{{errorMsg}}</div>-->
                </div>
            </div>
            <el-table
                    :data="errTableData"
                    border
                    height="200"
                    :stripe="true"
                    header-row-class-name="headerBackgroundColor"
                    header-align="center"
                    class="response-table"
                    style="width: 100%">

                <el-table-column
                        type="index"
                        width="50">
                </el-table-column>
                <el-table-column
                        label="错误信息"
                        align="center"
                        :show-overflow-tooltip="true">
                    <template  slot-scope="scope">
                        <div v-if="Number(scope.row.line)!==0">
                            第{{scope.row.line}}行&nbsp;&nbsp;{{scope.row.msg}}
                        </div>
                        <div v-if="Number(scope.row.line)===0">
                            {{scope.row.msg}}
                        </div>
                    </template>

                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
            <slot name="footer"></slot>
            <span>
                 <el-button size="mini" @click="handleCancel">关闭</el-button>
            </span>
            </span>
        </el-dialog>
        <el-dialog v-if="showDialogType===2"
                   :title="dialogTitleText"
                   center
                   :requestData="requestData"
                   :visible.sync="showDialog"
                   :show-close="true"
                   @close="dialogClose"
                   :modal-append-to-body="modalAppendToBody"
                   :close-on-click-modal="false"
                   class="response-middle-dialog">

            <el-form ref="ImportForm" :rules="ImportRules" status-icon :model="ImportConfigData"
                     label-width="90px">
                <div class="response-dialog-form-input">
                    <el-form-item class="pc-item" label="是否排重：">
                        <el-select v-model="repeat" placeholder="请选择">
                            <el-option :label="item.label" :value="item.value" v-for="item in repeatData"
                                       :key="item.value"></el-option>
                        </el-select>
                        <span class="item-note">（排重操作大数据导入会使系统导入时间过长，200条以上请谨慎操作！）</span>
                    </el-form-item>
                   <!-- <div>（排重操作大数据导入会使系统导入时间过长，200条以上请谨慎操作！）</div>-->
                    <el-form-item label="试题分类：" prop="selectSTClassify">
                        <mta-select-input-tree
                                class="mta-select-input"
                                placeholder="请选择考试分类"
                                ref="ccc"
                                :select-date.sync="ImportConfigData.selectSTClassify"
                                :original-tree-data="STClassifyArr"
                                :tree-default-props="treeStructure"
                                current-ref="ksClassify"></mta-select-input-tree>
                    </el-form-item>
                    <!--<el-form-item label="试题难度：" prop="selectLevel">
                        <mta-select-input-tree
                                class="mta-select-input2"
                                placeholder="请选择考试分类"
                                :select-date.sync="ImportConfigData.selectLevel"
                                :original-tree-data="STLevelArr"
                                :tree-default-props="treeStructure"
                                ref="ccc3"
                                current-ref="ksClassify"></mta-select-input-tree>
                    </el-form-item>-->
                </div>
            </el-form>
            <div class="import-head">
                <div class="downloadTem">
                    <div>
                        <span class="wordChenked" style="cursor: pointer" :class="wordChenked === 0 ? 'wordChenked' : 'wordUnChenked'"
                              @click="downloadFun('word')"></span>
                        <span style="cursor: pointer" :class="excelChenked === 0 ? 'excelUnChenked' : 'excelChenked'"
                              @click="downloadFun('excel')"></span>
                        <span style="display: block;cursor: pointer">下载</span>
                    </div>
                </div>
                <div class="import-jt import-jt-narrow">
                    <span></span>
                </div>
                <div class="downloadTem">
<!--                    <span class="testChenked"></span>-->
                    <el-upload
                            class="upload-demo"
                            action="https://jsonplaceholder.typicode.com/posts/"
                            :show-file-list="false"
                            :http-request="importFun"
                    >
                        <div style="display: flex;flex-direction: column;margin-top: -8px">
                            <span class="testChenked"></span>
                            <span>{{dataImportText}}</span>
                        </div>
                    </el-upload>
                </div>
            </div>
            <div class="drjg-box">
                <div style="text-align: center">导入结果</div>
                <div>
                    <div class="successSpan">导入成功数据：<span class="color-p">{{listSuccess}}条</span></div>
                    <div  class="errorSpan">导入失败数据：<span style="color: #e51c23;" >{{listError}}条</span></div>
                </div>
            </div>
            <el-table
                    :data="errTableData"
                    border
                    height="200"
                    :stripe="true"
                    header-row-class-name="headerBackgroundColor"
                    header-align="center"
                    class="response-table"
                    style="width: 100%">

                <el-table-column
                        type="index"
                        width="50">
                </el-table-column>
                <el-table-column
                        label="错误信息"
                        min-width="200"
                        :show-overflow-tooltip="true">
                    <template  slot-scope="scope">
                        <div v-if="Number(scope.row.line)!==0">
                            第{{scope.row.line}}行&nbsp;&nbsp;{{scope.row.msg}}
                        </div>
                        <div v-if="Number(scope.row.line)===0">
                            {{scope.row.msg}}
                        </div>
                    </template>

                </el-table-column>
                <el-table-column
                        prop="topicDry"
                        label="题干"
                        :show-overflow-tooltip="true"
                        min-width="200">
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
            <slot name="footer"></slot>
            <span>
                 <el-button size="mini" @click="handleCancel">关闭</el-button>
            </span>
            </span>
        </el-dialog>
        <el-dialog v-if="showDialogType===3"
                   :title="dialogTitleText"
                   center
                   :visible.sync="showDialog"
                   :requestData="requestData"
                   :show-close="true"
                   @close="dialogClose"
                   :modal-append-to-body="modalAppendToBody"
                   :close-on-click-modal="false"
                   class="response-middle-dialog">
            <div class="import-head">
                <div class="downloadTem" @click="downloadFun" style="cursor: pointer">
                    <div class="img-box">
                        <img :src="importDownImg" alt="">
                    </div>
                    <span >下载模版</span>
                </div>
                <div class="import-jt">
                    <span></span>
                </div>
                <div class="downloadTem">

                    <el-upload
                            class="upload-demo"
                            action="https://jsonplaceholder.typicode.com/posts/"
                            :show-file-list="false"
                            :http-request="importFun"
                    >
                        <div class="img-box">
                            <img :src="importShijuanImg" alt="">
                        </div>
                        <span>{{dataImportText}}</span>
                    </el-upload>
                </div>
            </div>
            <div class="drjg-box">
                <span>导入结果</span>
                <div>
                    <div class="successSpan">导入成功数据：<span class="color-p">{{listSuccess}}条</span></div>
                    <div class="errorSpan">导入失败数据：<span style="color: #e51c23">{{listError}}条</span></div>
                </div>
            </div>
            <el-table
                    :data="errTableData"
                    border
                    height="200"
                    :stripe="true"
                    header-row-class-name="headerBackgroundColor"
                    header-align="center"
                    class="response-table"
                    style="width: 100%">

                <el-table-column
                        type="index"
                        width="50">
                </el-table-column>
                <el-table-column
                        label="错误信息"
                        align="center"
                        :show-overflow-tooltip="true">
                    <template  slot-scope="scope">
                        <div v-if="Number(scope.row.line)!==0">
                            第{{scope.row.line}}行&nbsp;&nbsp;{{scope.row.msg}}
                        </div>
                        <div v-if="Number(scope.row.line)===0">
                            {{scope.row.msg}}
                        </div>
                    </template>

                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
            <slot name="footer"></slot>
            <span>
                 <el-button size="mini" @click="handleCancel">关闭</el-button>
            </span>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { getBaseUrlFromCommon ,getImg}                                                                from '@/utils/common.js';
    import { getUploadImg }                                                                        from '@/api/AlCloud.js';
    import axios                                                                                   from 'axios';
    import MtaSelectInputTree
                                                                                                   from '@/components/management/Layout/SelectInput/SelectInputTree';
    import { getShitiClassifyList, getShitiLevelList, getShitiKnowledgeList,uploadTemplate } from '@/api/exam';
    import { getAdminUserImport }                                                                  from '@/api/user';

    //  describe: 组件说明 author: Wgy date:2019-10-31
    //   <template-import :dialogVisible.sync="optenFlag" templateType="user" :requestData="requestData" :requestUrl="requestUrl"></template-import>
    // 必传项 ：templateType下载模版类型 （必传根据自己需要添加） 如 user  对应的下载地址为 如下： address.user
    //必传项 ：requestUrlType 导入模版获取成功失败条数类型  如下方 shitiImport  （写对应的接口地址格式按照例子写）
    //必传项 :dialogVisible.sync    弹窗flag
    // 弹窗title文字 dialogTitleText  导入模版文字 dataImportText  dlWidth弹窗宽度
    // 非必传项  showDialogType （默认为1） 1为模版下载 2为 试题批量导入
    /*   非必传项  requestData （接口需要额外入参 使用） 父页面 写在computed 中
    *   computed:   {
              requestData: function (val) {
                  return {
                      page:  1,
                      page2:  2,
                  };
              },
          },
    *
    * */
    export default {
        name:       'import',
        components: {
            MtaSelectInputTree,
        },
        data() {
            const validate1 = (rule, value, callback) => {
                const data = JSON.parse(JSON.stringify(value));
                if (data && data.id !== undefined && data.id !== 0) {
                    callback();
                } else {
                    callback(new Error('请选择知识点分类'));
                }
            };
            const validate2 = (rule, value, callback) => {
                const data = JSON.parse(JSON.stringify(value));
                if (data && data.id !== undefined && data.id !== 0) {
                    callback();
                } else {
                    callback(new Error('请选择试题分类'));
                }
            };
            const validate3 = (rule, value, callback) => {
                const data = JSON.parse(JSON.stringify(value));
                if (data && data.id !== undefined && data.id !== 0) {
                    callback();
                } else {
                    callback(new Error('请选择试题难度'));
                }
            };
            return {
                //模版下载地址汇总
                address:          {
                    user:    '/open/template/%E7%94%A8%E6%88%B7%E6%89%B9%E9%87%8F%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx',
                    xianxia: '/open/template/%E7%BA%BF%E4%B8%8B%E6%88%90%E7%BB%A9%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx',
                    word:    '/open/template/%E8%AF%95%E9%A2%98%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.docx',
                    excel:   '/open/template/%E8%AF%95%E9%A2%98%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx',
                    offlineResults: '/open/template/%E7%BA%BF%E4%B8%8B%E6%88%90%E7%BB%A9%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx',
                    kaoshiAdduser:'/open/template/%E6%B7%BB%E5%8A%A0%E7%94%A8%E6%88%B7%E6%A8%A1%E6%9D%BF.xlsx'
                },
                repeatData:[
                    {
                    value: false,
                    label: '是'
                     },
                    {
                        value: true,
                        label: '否'
                    },
                ],
                repeat:true,
                //formLabelWidth:    '120px',
                showDialog:       this.dialogVisible,
                wordChenked:      0, //word flag
                excelChenked:     1, //excel flag
                listSuccess:      '',//成功数量
                listError:        '',//失败数量
                errTableData:     [],
                errorMsg:         '',//错误信息
                STClassifyArr:    [],
                STLevelArr:       [],
                ImportConfigData: {
                    selectSTClassify: {},
                    selectLevel:      {},
                },
                treeStructure:    {
                    children: 'children',
                    label:    'lable',
                },
                ImportRules:      {
                    selectSTClassify: [
                        { required: true, validator: validate2 },
                    ],
                    /*selectLevel:      [
                        { required: true, validator: validate3 },
                    ],*/
                },
                //青谷麦塔图片区分
                importDownImg:getImg('default/import-down','png'),
                importImg:getImg('default/import-import','png'),
                importShijuanImg:getImg('default/import-shijuan','png'),
            };
        },
        props:      {
            //弹窗显隐 flag
            dialogVisible:   {
                type:    Boolean,
                require: true,
            },
            modalAppendToBody:   {
                type:    Boolean,
                require: true,
            },
            // 下载模版类型 （必传根据自己需要添加）
            templateType:    {
                type:    String,
                require: true,
            },
            // 1为模版下载 2为 试题批量导入
            showDialogType:  {
                type:    Number,
                default: 1,
            },
            //入参 默认fileUrl
            requestData:     {
                type: Object,
            },
            // 导入试题后调用接口类型（如：提交）
            requestUrl:  {
                type:    String,
                require: true,
            },
            // 导入模版文字描述
            dataImportText:  {
                type:    String,
                default: '导入试卷分类',
            },
            // 弹窗title  文字描述
            dialogTitleText: {
                type:    String,
                default: '批量导入试卷分类',
            },
            //弹窗宽度
            dlWidth:         {
                type:    String,
                default: '50%',
            },
        },
        methods:    {
            //  describe: 切换图片 author: Wgy date:2019-10-31
            changeImg(data) {
                if (data === 0) {
                    this.wordChenked = 0;
                    this.excelChenked = 0;
                } else {
                    this.wordChenked = 1;
                    this.excelChenked = 1;
                }
            },
            //  describe: 下载模版 author: Wgy date:2019-10-30
            downloadFun(opt) {
                if (this.showDialogType === 1) {
                    window.location.href = getBaseUrlFromCommon() + this.address[this.templateType];
                } else if (this.showDialogType === 2) {
                    if (opt && opt === 'word') {
                        window.location.href = getBaseUrlFromCommon() + this.address.word;
                    } else if (opt && opt === 'excel') {
                        window.location.href = getBaseUrlFromCommon() + this.address.excel;
                    }
                }else if(this.showDialogType === 3){
                    window.location.href = getBaseUrlFromCommon() + this.address[this.templateType];
                }
            },
            importFun(params) {
                if (!params) {
                    return false;
                }
                const suffixList = params.file.name.split('.');
                const options = {
                    prefix: 'temp/',
                    suffix: suffixList[1],
                };
                getUploadImg(options).then((res) => {
                    if (res.code === 0) {
                        // 二进制文件通过forData对象进行传递
                        const FormDataForAl = new FormData();
                        const multipartParams = Object.assign({}, res.data, {
                            Filename:              `images/${params.filename}`,
                            success_action_status: '200',
                        });
                        // 参数数据
                        FormDataForAl.append('key', multipartParams.key);
                        FormDataForAl.append('policy', multipartParams.policy);
                        FormDataForAl.append('signature', multipartParams.signature);
                        FormDataForAl.append('OSSAccessKeyId', multipartParams.accessid);
                        FormDataForAl.append('success_action_status', multipartParams.success_action_status);
                        // OSS要求, file放到最后
                        FormDataForAl.append('file', params.file);
                        window.loading1 = this.$loading();
                        axios.post(multipartParams.uploadUrl, FormDataForAl).then(alRes => {
                            if (alRes.status === 200) {
                                const fileUrl = `${multipartParams.downloadUrl}/${multipartParams.key}`;
                                let fromParam = {
                                    stClassifyId:  this.ImportConfigData.selectSTClassify.id,
                                    stLevelId:     this.ImportConfigData.selectLevel.id,
                                    url:           fileUrl,
                                    repeat:this.repeat
                                };
                                let req = {};
                                let url = this.requestUrl;
                                if (this.showDialogType === 1||this.showDialogType === 3) {
                                    req = Object.assign(fromParam, this.requestData);
                                    uploadTemplate(req,url)
                                    .then((res) => {
                                       this.getDataResults(res)
                                    }).catch(err => {
                                        window.loading1.close();
                                    });
                                } else if (this.showDialogType === 2) {
                                    req = Object.assign(fromParam,this.requestData);
                                    this.$refs['ImportForm'].validate((valid) => {
                                        if (valid) {
                                            uploadTemplate(req,url)
                                            .then((res) => {
                                                this.getDataResults(res)
                                            }).catch(err => {
                                                window.loading1.close();
                                            });
                                        } else {
                                            window.loading1.close();
                                            this.$message.error('校验失败');
                                        }
                                    });
                                }else if(this.showDialogType === 3){
                                    req = Object.assign(fromParam,this.requestData);
                                    uploadTemplate(req,url)
                                    .then((res) => {
                                        this.getDataResults(res)
                                    }).catch(err => {
                                        window.loading1.close();
                                    });
                                }
                            }
                        });
                    }

                });
            },

            //获得成功或者失败信息
            getDataResults(res) {
                if (res.code === 0) {
                    this.errTableData = [];
                    if (res.data.fail) {
                        res.data.failList.forEach((item) => {
                            const opt = {
                                msg: item.msg,
                                line: item.line,
                                topicDry: item.data.name,
                            };
                            this.errTableData.push(opt);
                        });
                    }
                    this.listError = res.data.fail;
                    this.listSuccess = res.data.success;
                    if(res.data.userList){
                        this.$emit('importSuccess',res.data.userList);
                    }else {
                        this.$emit('importSuccess');
                    }
                }
                window.loading1.close();
            },
            // 下拉树请求
            getShitiClassifyList() {
                getShitiClassifyList().then(res => {
                    if (res.code === 0) {
                        this.STClassifyArr = res.data.children;
                    }
                });
            },
            // 下拉树请求
            getShitiLevelList() {
                getShitiLevelList().then(res => {
                    if (res.code === 0) {
                        this.STLevelArr = res.data.children;
                    }
                });
            },
            handleCancel() {
                this.$emit('update:dialogVisible', false);
            },
            dialogClose() {
                if (this.showDialogType === 1) {
                    this.$emit('update:dialogVisible', false);
                    this.listError = '';
                    this.listSuccess = '';
                    this.errTableData = [];
                } else {
                    this.$emit('update:dialogVisible', false);
                    this.errTableData = [];
                    this.listError = '';
                    this.listSuccess = '';
                    this.$refs.ccc.clearInputData();
                    this.$refs.ccc3.clearInputData();
                    this.$refs.ImportForm.resetFields();
                }
                // description: 弹窗关闭事件; author: Wxy; date: 2019/11/25
                this.$emit('dialogClose', true);
            },
        },
        created() {

        },
        watch:      {
            dialogVisible: {
                handler() {
                    this.showDialog = this.dialogVisible;
                    if (this.showDialogType === 1 ||this.showDialogType === 3) {
                        // 待添加
                    } else if(this.showDialog&&this.showDialogType === 2) {
                        this.getShitiClassifyList();
                        this.getShitiLevelList();
                    }
                },
                immediate: true,
            },
        },
    };
</script>
