<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="handleImport">导入</el-button>
                <el-button type="primary" @click="showExportDialog = true">导出</el-button>
        </el-card>
        <el-card style="margin-top: 10px">
            <el-table v-loading="listLoading" :data="tableData.results" :hieght="tableHeight" border fit stripe 
                highlight-current-row>
                <el-table-column type="index" width="50" />
                <el-table-column label="公司名称">
                    <template slot-scope="scope">{{ scope.row.name }}</template>
                </el-table-column>
                <el-table-column label="资质名称">
                    <template slot-scope="scope">{{ scope.row.quali_name }}</template>
                </el-table-column>
                <el-table-column label="评审方法">
                    <template slot-scope="scope">
                        <span>{{ cateOptions[scope.row.judging_method] }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="评审类型">
                    <template slot-scope="scope">{{ typesOp[scope.row.judging_type] }}</template>
                </el-table-column>
                <el-table-column label="新增参数(个)">
                    <template slot-scope="scope">{{ scope.row.add_param }}</template>
                </el-table-column>
                <el-table-column label="评审日期">
                    <template slot-scope="scope">{{ scope.row.review_date }}</template>
                </el-table-column>
                <el-table-column label="现有场所数量">
                    <template slot-scope="scope">{{ scope.row.now_count }}</template>
                </el-table-column>
                <el-table-column label="新增场所数量">
                    <template slot-scope="scope">{{ scope.row.add_count }}</template>
                </el-table-column>

                <el-table-column align="center" label="操作" width="120px" fixed="right">
                    <template slot-scope="scope">
                        <el-link :disabled="!checkPermission(['infoCollect_RS'])" type="primary" size="small"
                            @click="handleEdit(scope)">编辑</el-link>
                        <el-divider direction="vertical"
                            v-if="checkPermission(['infoCollect_RS']) && checkPermission(['infoCollect_RS'])"></el-divider>
                        <el-link :disabled="!checkPermission(['infoCollect_RS'])" type="danger" size="small"
                            @click="handleDelete(scope)">删除</el-link>
                    </template>
                </el-table-column>
            </el-table>
            <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="name">
                    <el-input v-model="Content.name" placeholder="公司名称" />
                </el-form-item>
                <el-form-item label="资质名称" prop="quali">
                    <template>  
                        <el-select v-model="Content.quali" placeholder="请选择" @visible-change="handleVisibleChange">  
                            <el-option  
                                v-for="item in options"  
                                :key="item.id"  
                                :label="item.name"  
                                :value="item.id">  
                            </el-option>  
                        </el-select>  
                    </template>
                </el-form-item>
                <el-form-item label="评审方法" prop="judging_method">
                    <el-select v-model="Content.judging_method" placeholder="请选择">
                        <el-option
                        v-for="item in method_options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="评审类型" prop="judging_type">
                    <el-select v-model="Content.judging_type" placeholder="请选择">
                        <el-option
                            v-for="item in type_options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                            </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="新增参数(个)" prop="add_param">
                    <el-input v-model="Content.add_param" placeholder="新增参数" />
                </el-form-item>
                <el-form-item label="现有场所数量" prop="now_count">
                    <el-input-number
                        v-model="Content.now_count"
                        :min="0"
                        controls-position="right"
                        :step="1"
                        step-strictly="true"
                    />
                </el-form-item>
                <el-form-item label="新增场所数量" prop="add_count">
                    <el-input-number
                        v-model="Content.add_count"
                        :min="0"
                        controls-position="right"
                        :step="1"
                        step-strictly="true"
                    />
                </el-form-item>
                <el-form-item label="评审日期" prop="review_date">
                    <el-date-picker
                        v-model="Content.review_date"
                        type="date"
                        placeholder="选择日期"
                        value-format="yyyy-MM-dd"
                        style="width:50%"
                    ></el-date-picker>
                </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>
        <el-dialog
            :visible.sync="impDialogVisible"
            title="导入"
            :close-on-click-modal="false"
        >
          <el-form
            ref="Form"
            label-width="80px"
            label-position="right"
            :rules="rule"
            >
            <el-form-item label="下载模板" prop="path">
              <a :href="downloadUrl">点击下载模板</a>
            </el-form-item>
            <el-form-item label="导入文件" prop="file">
                <el-upload
                    ref="upload"
                    :action="upUrl"
                    :on-success="handleUpSuccess"
                    :on-remove="handleRemove"
                    :on-preview="handlePreview"
                    :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="close_dialog">取消</el-button>
            <el-button type="primary" @click="submitUpload" :disabled="saveLoading">确认</el-button>
          </div>
        </el-dialog>
        <el-dialog  
      title="选择时间范围"  
      :visible.sync="showExportDialog"  
      width="50%"  
      @close="showExportDialog = false"  
    >  
      <el-form :model="exportForm" ref="exportForm" label-width="120px">  
        <el-form-item label="开始日期">  
          <el-date-picker  
            v-model="exportForm.startDate"  
            type="date"  
            placeholder="选择开始日期"  
          ></el-date-picker>  
        </el-form-item>  
        <el-form-item label="结束日期">  
          <el-date-picker  
            v-model="exportForm.endDate"  
            type="date"  
            placeholder="选择结束日期"  
          ></el-date-picker>  
        </el-form-item>  
      </el-form>  
      <span slot="footer" class="dialog-footer">  
        <el-button @click="showExportDialog = false">取消</el-button>  
        <el-button type="primary" @click="handleExport">确定</el-button>  
      </span>  
        </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 { getDictList, getDictTypeList } from "@/api/dict";
import { createRs, delRs, updateRs, getMyRs, getRs, exportData, impData } from "@/api/review";
import { getMyQi} from "@/api/qualificationInfo";
import { upUrl, upHeaders } from "@/api/file";
import { saveAs } from 'file-saver';  
import XLSX from 'xlsx';  
const defaultContent = {
    name: "",
    qualification_name: "",
    quali:"",
    judging_method: "",
    judging_type: "",
    add_param: "",
    review_date: "",
    now_count: "",
    add_count: ""
};

export default {
    components: { Pagination, Treeselect },
    data(){
        return {
            form: {
                name: "",
                qualification_name: "",
                judging_method: "",
                judging_type: "",
                add_param: "",
                review_date: "",
                now_count: "",
                add_count: "",
                quali:""
            },
            method_options: [{value: 0,label: '文审'},{value: 10,label: '现场'}],
            cateOptions: {
                0:'文审',
                10:'现场'
            },
            typesOp: {
                0:'初次',
                10:'扩项',
                20:'变更',
                30:'复评',
                40:'迁址'
            },
            selectedValue: '',
            options: [],
            isoading: false, //是否正在加载数据
            type_options: [{
            value: 0,
            label: '初次'},
            {
            value: 10,
            label: '扩项'},
            {
            value: 20,
            label: '变更'},{
            value: 30,
            label: '复评'},
            {
            value: 40,
            label: '迁址'}],
            upHeaders: upHeaders(),
            upUrl: upUrl(),
            fileList: [],
            Content: defaultContent,
            typeOptions: [],
            listLoading: false,
            dialogVisible: false,
            showExportDialog: false,
            saveLoading:false,
            impDialogVisible: false,
            downloadUrl: process.env.VUE_APP_BASE_API,
            impForm:{
                file:''
              },
            exportForm: { 
                startDate: '', // 开始日期  
                endDate: '', // 结束日期  
                        },
            listQuery: {
                page: 1,
                page_size: 20,
            },
            tableData: {
                count: 0
            },
            dialogType: "new",
            rule: {
                name: [{ required: true, message: "请输入名称", trigger: "blur" }],
            },
            filterOrgText: "",
            tableHeight: null,
        };
    },
    computed: {},
    watch: {
        filterOrgText(val) {
            this.$refs.tree.filter(val);
        },
    },
    mounted() {
        let that = this;
        let height1 = document.getElementsByClassName('app-main')[0].clientHeight;
        let height2 = document.getElementsByClassName('elHeader')[0].clientHeight;
        that.tableHeight = height1 - height2 - 70;
        console.log(that.tableHeight)
        that.getList();

    },
    methods: {
        getTableList() {
            this.getList();
        },
        handleImport(){
          this.impDialogVisible = true;
          let file_url = '';
          file_url = "media/default/评审情况-评审情况统计表.xlsx";
          let base_url = this.downloadUrl.substr(0, this.downloadUrl.length - 3);
          this.downloadUrl = base_url+file_url;
        },
        close_dialog(){
            this.impDialogVisible = false;
            this.fileList = [];
            this.impForm.file = '';
        },
        submitUpload() {
        this.$refs.upload.submit();
        this.impDialogVisible = false;
        this.saveLoading = true;
            impData(this.impForm).then(res=>{
                console.log(this.impForm)
                if(res.code>=200){
                    this.saveLoading = false;
                    this.$message.success("提交成功");
                    this.getList();
                }else{
                    this.$message.error(res.message);
                    this.saveLoading = false;
                }
            })
      },
        handlePreview(file) {
            if ("url" in file) {
                window.open(file.url);
            } else {
                window.open(file.response.data.path);
            }
        },
        handleUpSuccess(res, file, filelist) {
            this.Content.file = res.data.id;
            this.impForm.file = res.data.path;
        },
        handleRemove(file, filelist) {
            this.Content.file = null;
            this.fileList = [];
            this.impForm.file = '';
        },
        checkPermission,
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        getList() {
            this.listLoading = true;
            this.tableData.results =[];
            this.tableData.count =0;
            getMyRs(this.listQuery).then((response) => {
                console.log(response);
                if (response.data) {
                  this.tableData = response.data;
                }
                this.listLoading = false;
            });
        },
        handleExport() {
            if (!this.exportForm.startDate || !this.exportForm.endDate) {  
                this.$message.error('请选择完整的起止日期！');  
                return;}
                console.log(this.exportForm)
                exportData(this.exportForm).then((response) => {
                        if (response.data) {
                        let filename = '评审情况表.xlsx';
                        let tableData = response.data;
                        console.log(tableData)
                        const ws = XLSX.utils.json_to_sheet(tableData.results);  
                        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 = '';
        },
        handleFilter() {
            this.listQuery.page = 1;
            this.getList();
        },
        handleAddFile() {
            this.Content = Object.assign({}, defaultContent);
            this.dialogType = "new";
            this.dialogVisible = true;
            this.fileList = []
            this.$nextTick(() => {
                this.$refs["Form"].clearValidate();
            });
        },
        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 delRs(scope.row.id);
                    this.getList();
                    this.$message.success("成功");
                })
                .catch((err) => {
                    console.error(err);
                });
        },
        async confirm(form) {
            this.$refs[form].validate((valid) => {
                if (valid) {
                    const isEdit = this.dialogType === "edit";
                    if (isEdit) {
                        console.log(this.Content);
                        updateRs(this.Content.id, this.Content).then((response) => {
                        if (response.data) {
                        this.tableData = response.data;
                        }
                        this.listLoading = false;
                        this.dialogVisible = false;
                        this.getTableList();
                });
                    } else {
                        createRs(this.Content).then((response) => {
                        if (response.data) {
                        this.tableData = response.data;
                        }
                        this.listLoading = false;
                        this.dialogVisible = false;
                        this.getTableList();
            });
                    }
                } else {
                    return false;
                }
            });
        },
        async handleVisibleChange(val) {  
            if (val) {  
                // 当下拉框变为可见时，调用接口获取数据  
                if (!this.isLoading) {  
                this.isLoading = true;  // 设置加载状态，防止重复请求  
                try {  
                    const response = await this.fetchOptions(); 
                    console.log(response,"ceshi");
                     
                } catch (error) {  
                    // 处理错误  
                    console.error(error);  
                } finally {  
                    this.isLoading = false;  // 无论成功还是失败，都重置加载状态  
                }  
                }  
            }  
        },
        fetchOptions() {
            getMyQi().then((response) => {
                console.log(response);
                if (response.data) {
                    this.options = response.data.results; 
                }
            });
        }
    },
           
};
</script>
<style></style>
