<template>
    <div class="app-container">
        <el-card class="elHeader">
            <el-button type="primary" icon="el-icon-plus"  @click="handleAddFile">新增</el-button>
            <el-button type="primary" @click="handleExport">导出</el-button>
        </el-card>
        <el-card style="margin-top: 10px">
            <el-table v-loading="listLoading" 
            :data="tableData.results"  
            border fit stripe
                highlight-current-row>
                <el-table-column type="index" width="50" />
                <el-table-column label="公司名称" prop="company_name"></el-table-column>
                <el-table-column label="资质名称" prop="name"></el-table-column>
                <el-table-column label="资质类型" prop="quali_type">
                    <template slot-scope="scope">
                        <span>{{ac_options[scope.row.quali_type]}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="发证单位" prop="org"></el-table-column>
                <el-table-column label="发证日期" prop="org_date"></el-table-column>
                <el-table-column label="截至日期" prop="expiration_date"></el-table-column>
                <el-table-column label="资质范围" prop="scope"></el-table-column>
                <el-table-column label="参数数量" prop="number"></el-table-column>
                <el-table-column align="left" label="证书" prop="cert_path">
                    <template slot-scope="scope">
                        <img v-if="scope.row.cie_path && checkPermission(['infoCollect_QIN_Down'])" :src="scope.row.cie_path" @click="handlePictureCardPreview(scope.row.cie_path)" alt="图片" height="30" width="50"/>
                    </template>
                </el-table-column>
                <el-table-column label="变更日期" prop="change_date"></el-table-column>
                <el-table-column align="center" label="操作" width="120px" fixed="right">
                    <template slot-scope="scope">
                        <el-link v-if="checkPermission(['infoCollect_QIN'])" type="primary" size="small"
                            @click="handleEdit(scope)">编辑</el-link>
                        <el-divider direction="vertical"
                            v-if="checkPermission(['infoCollect_QIN']) && checkPermission(['infoCollect_QIN'])"></el-divider>
                        <el-link v-if="checkPermission(['infoCollect_QIN'])" type="danger" size="small"
                            @click="handleDelete(scope)">删除</el-link>
                        <el-link type="primary"  @click="handleChange(scope)">变更记录</el-link>     
                    </template>
                </el-table-column>
            </el-table>
            <el-dialog title="变更记录" :visible.sync="dialogTableVisible">  
                <el-table :data="changeTableData" style="width: 100%"> 
                    <el-table-column label="公司名称" prop="company_name"></el-table-column>
                    <el-table-column label="变更时间" prop="change_time" ></el-table-column>
                    <el-table-column prop="change_reason" label="变更原因"></el-table-column>
                    <el-table-column label="资质名称" >
                        <template v-slot="scope">  
                            <span>{{scope.row.val_new.name}}</span>  
                        </template>  
                    </el-table-column>   
                    <el-table-column label="变更详情" width="500">  
                        <template slot-scope="scope">  
                        <el-tag v-for="(diff, index) in scope.row.difference" :key="index">  
                            {{ resultsMap[diff.name] }}: {{ diff.old }} -> {{ diff.new }}  
                        </el-tag>  
                        </template>  
                    </el-table-column>
                </el-table>  
            </el-dialog>
            <pagination v-show="tableData.count > 0" :total="tableData.count" :page.sync="listQuery.page"
                :limit.sync="listQuery.page_size" @pagination="getTableList" />
        </el-card>
        <el-dialog :visible.sync="dialogVisible" :title="dialogType === 'edit' ? '编辑' : '新增'">
            <el-form ref="Form" :model="Content" label-width="80px" label-position="right" :rules="rule">
                <el-form-item label="公司名称" prop="company_name">
                    <el-input v-model="Content.company_name" placeholder="公司名称"/>
                </el-form-item>
                <el-form-item label="资质名称" prop="name">
                    <el-input v-model="Content.name" placeholder="资质名称"/>
                </el-form-item>
                <el-form-item label="资质类型">
                    <el-select 
                        v-model="Content.quali_type"
                        placeholder="请选择"
                        >
                        <el-option
                            v-for="item in activateOptions"
                            :key="item.value"
                            :label="item.key"
                            :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="发证单位" prop="org">
                    <el-input v-model="Content.org" ></el-input>     
                </el-form-item>
                <el-form-item label="发证日期" prop="org_date">
                    <el-date-picker
                        v-model="Content.org_date"
                        type="date"
                        placeholder="选择日期"
                        value-format="yyyy-MM-dd"
                        style="width:50%"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="截至日期" prop="expiration_date">
                    <el-date-picker
                        v-model="Content.expiration_date"
                        type="date"
                        placeholder="选择日期"
                        value-format="yyyy-MM-dd"
                        style="width:50%"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="资质范围" prop="scope">
                    <el-input v-model="Content.scope" ></el-input> 
                </el-form-item>
                <el-form-item label="参数数量" prop="number" >
                    <el-input-number
                        v-model="Content.number"
                        :min="1"
                        controls-position="right"
                        :step="1"
                    />
                </el-form-item>
                <el-form-item label="证书上传" prop="file">
                    <el-upload
                    ref="upload"
                    :action="upUrl"
                    :on-success="handleUpSuccess"
                    :on-remove="handleRemove"
                    :on-preview="handlePreview"
                    :before-upload="beforeUpload"
                    :headers="upHeaders"
                    :file-list="fileList"
                    :limit="1"
                    accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.zip">
                    <el-button size="small" type="primary">上传证书</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div style="text-align: right">
                <el-button type="danger" @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirm('Form')">确认</el-button>
            </div>
        </el-dialog>
  
    </div>
</template>
<script>
import checkPermission from "@/utils/permission";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getAllQi, getQi, updateQi, createQi, delQi} from "@/api/qualificationInfo";
import { upUrl, upHeaders } from "@/api/file";
import { saveAs } from 'file-saver';  
import XLSX from 'xlsx'; 


const defaultContent = {
                company_name: "",
                name: "",
                quali_type: "",
                org: "",
                org_date: "",
                expiration_date: "",
                scope: "",
                number: "",
                cie_path: "",
                change_date: null
                };

export default {
    components: { Pagination, Treeselect },
    data(){
        return {
            form: {
                company_name: "",
                name: "",
                quali_type: "",
                org: "",
                org_date: "",
                expiration_date: "",
                scope: "",
                number: "",
                cie_path: "",
                change_date: null
            },
            upHeaders: upHeaders(),
            upUrl: upUrl(),
            fileList: [],
            Content: defaultContent,
            typeOptions: [],
            listLoading: false,
            dialogVisible: false,
            showExportDialog: false,
            dialogTableVisible:false,
            exportForm: { 
                startDate: '', // 开始日期  
                endDate: '', // 结束日期  
                        },
            listQuery: {
                page: 1,
                page_size: 20,
            },
            tableData: {
                count: 0
            },
            changeTableData:[],
            dialogType: "new",
            rule: {
                name: [{ required: true, message: "请输入名称", trigger: "blur" }],
            },
            filterOrgText: "",
            // tableHeight: '300px',
            activateOptions:[
                {key:'国家级',value:'国家级'},
                {key:'省级',value:'省级'}
                ],
            ac_options:{'国家级':'国家级', '省级':'省级'},
            resultsMap:{
                "company_name":"公司名称",
                "name":"资质名称",
                "quali_type":"资质类型",
                "org":"发证单位",
                "org_date":"发证日期",
                "expiration_date":"截至日期",
                "scope":"资质范围",
                "number":"参数数量",
                "cie_path":"证书路径",
            }
        }
    },
    mounted() {
                let that = this;
                let height1 = document.getElementsByClassName('app-main')[0].clientHeight;
                let height2 = document.getElementsByClassName('elHeader')[0].clientHeight;
                that.tableHeight = height1 - height2 - 70;
                that.getList();

            },
    methods: {
      
        //提交表单
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.dialogType == "new") {
                        this.addData();
                    } else {
                        this.editData();
                    }
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        getTableList(){
            this.getList()
            
        },
        handleExport() {
            getAllQi({page:0}).then((response) => {
                if (response.data) {
                let filename = '资质情况统计表.xlsx';
                let tableData = response.data;
                const ws = XLSX.utils.json_to_sheet(tableData);  
                const wb = XLSX.utils.book_new();  
                XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');  
                const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });  
                try {  
                    saveAs(new Blob([wbout], { type: 'application/octet-stream' }), filename);  
                } catch (e) { if(typeof console !== 'undefined') console.log(e, wbout); }  
                return;  
                }else {  
                    this.$message.error(data.message || '导出失败');  
                }  
            })
                    // this.showExportDialog = false; 
                    .catch(error => {  
                        this.$message.error('请求失败，请稍后再试');  
                        console.error(error);  
                    })  
                    .finally(() => {  
                        this.handleDialogClose(); 
                    });
        },
        handleDialogClose(){
            this.showExportDialog = false;
            this.startDate = '';
            this.endDate = '';
        },
        handlePreview(file) {
            if ("url" in file) {
                window.open(file.url);
            } else {
                window.open(file.response.data.path);
            }
        },
        handleUpSuccess(res, file, filelist) {
            this.Content.cie_path = res.data.path;
            this.Content.file = res.data.id;
        },
        beforeUpload(file) {
            const isLt10M = file.size / 1024 / 1024 < 10;
            if (!isLt10M) {
                this.$message.error("上传文件大小不能超过 10MB!");
            }
            return isLt2M;
        },
        handleRemove(file, filelist) {
            this.Content.file = null;
        },
        checkPermission,

        getList() {
            this.listLoading = true;
            getAllQi(this.listQuery).then((response) => {
                if (response.data) {
                  this.tableData = response.data;

                }
                this.listLoading = false;
            }
        );
        },

        handleAddFile() {
            this.Content = Object.assign({}, defaultContent);
            this.dialogType = "new";
            this.dialogVisible = true;
            this.fileList = []
            this.$nextTick(() => {
                this.$refs["Form"].clearValidate();
            });
        },
        handlePictureCardPreview(url){
            window.open(url);
        },
        handleEdit(scope) {
            this.Content = Object.assign({}, scope.row); // copy obj
            this.dialogType = "edit";
            this.dialogVisible = true;
            if (this.Content.file) {
                this.fileList = [
                    {
                        name: this.Content.file_.name,
                        url: this.Content.file,
                    },
                ];
            }
            this.$nextTick(() => {
                this.$refs["Form"].clearValidate();
            });
        },
        handleDelete(scope) {
            this.$confirm("确认删除?", "警告", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: "error",
            })
                .then(async () => {
                    await delQi(scope.row.id);
                    this.getList();
                    this.$message.success("成功");
                })
                .catch((err) => {
                    console.error(err);
                });
        },
        handleChange(scope) {
            this.listLoading = true;
            this.Content = Object.assign({}, scope.row); // copy obj
            this.changeTableData =[];
            this.dialogTableVisible=true;
            getQi(scope.row.id).then((response) => {
                if (response.data.count>0) {
                  this.changeTableData = response.data.results;
                  this.listLoading = false;
                }else{
                    alert('无变更记录')
                    this.dialogTableVisible=false;
                    this.listLoading = false;
                    return
                }
            });
        },

        async confirm(form) {
            this.$refs[form].validate((valid) => {
                if (valid) {
                    const isEdit = this.dialogType === "edit";
                    if (isEdit) {
                        console.log(this.Content);
                        updateQi(this.Content.id, this.Content).then((response) => {
                        // if (response.data) {
                        // this.tableData = response.data;
                        // }
                        this.listLoading = false;
                        this.dialogVisible = false;
                        this.getTableList();
                });
                    } else {
                        console.log(this.Content);
                        createQi(this.Content).then((response) => {
                        // if (response.data) {
                        //     this.tableData = response.data;
                        // }
                        this.listLoading = false;
                        this.dialogVisible = false;
                        this.getTableList();
            });
                    }
                } else {
                    return false;
                }
            });
        },
    },
           
};
</script>
<style></style>