<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" icon="el-icon-plus" @click="handleImport">导入</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" :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.address }}</template>
                </el-table-column>
                <el-table-column label="负责人">
                    <template slot-scope="scope">{{ scope.row.header }}</template>
                </el-table-column>
                <el-table-column label="负责人电话">
                    <template slot-scope="scope">{{ scope.row.tel }}</template>
                </el-table-column>
                <el-table-column label="负责人邮箱">
                    <template slot-scope="scope">{{ scope.row.email }}</template>
                </el-table-column>
                <el-table-column label="技术负责人">
                    <template slot-scope="scope">{{ scope.row.head_technology }}</template>
                </el-table-column>
                <el-table-column label="技术负责电话">
                    <template slot-scope="scope">{{ scope.row.tel_technology }}</template>
                </el-table-column>
                <el-table-column label="技术负责人邮箱">
                    <template slot-scope="scope">{{ scope.row.email_technology }}</template>
                </el-table-column>
                <el-table-column label="质量负责人">
                    <template slot-scope="scope">{{ scope.row.head_quality }}</template>
                </el-table-column>
                <el-table-column label="质量负责人电话">
                    <template slot-scope="scope">{{ scope.row.tel_quality }}</template>
                </el-table-column>
                <el-table-column label="质量负责人邮箱">
                    <template slot-scope="scope">{{ scope.row.email_quality }}</template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="120px" fixed="right">
                    <template slot-scope="scope">
                        <el-link v-if="currentDept=scope.row.belong_dept" :disabled="!checkPermission(['infoCollect_LC'])" type="primary" size="small"
                            @click="handleEdit(scope)">编辑</el-link>
                        <el-divider direction="vertical"
                            v-if="checkPermission(['infoCollect_LC']) && checkPermission(['infoCollect_LC'])"></el-divider>
                        <el-link v-if="currentDept=scope.row.belong_dept" :disabled="!checkPermission(['infoCollect_LC'])" 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="address">
                    <el-input v-model="Content.address" placeholder="" />
                </el-form-item>
                <el-form-item label="负责人" prop="header">
                    <el-input v-model="Content.header" placeholder="" />
                </el-form-item>
                <el-form-item label="负责人电话" prop="tel">
                    <el-input v-model="Content.tel" placeholder="" />
                </el-form-item>
                <el-form-item label="负责人邮箱" prop="email">
                    <el-input v-model="Content.email" placeholder="" />
                </el-form-item>
                <el-form-item label="技术负责人" prop="head_technology">
                    <el-input v-model="Content.head_technology" placeholder="" />
                </el-form-item>
                <el-form-item label="技术负责人电话" prop="tel_technology">
                    <el-input v-model="Content.tel_technology" placeholder="" />
                </el-form-item>
                <el-form-item label="技术负责人邮箱" prop="email_technology">
                    <el-input v-model="Content.email_technology" placeholder="" />
                </el-form-item>
                <el-form-item label="质量负责人" prop="head_quality">
                    <el-input v-model="Content.head_quality" placeholder="" />
                </el-form-item>
                <el-form-item label="质量负责人电话" prop="tel_quality">
                    <el-input v-model="Content.tel_quality" placeholder="" />
                </el-form-item>
                <el-form-item label="质量负责人邮箱" prop="email_quality">
                    <el-input v-model="Content.email_quality" placeholder="" />
                </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">确认</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 { getDictList, getDictTypeList } from "@/api/dict";
import {createCt, del_contact, updateContact, getCtAll, getCt, impData} from "@/api/contacts";
import { upUrl, upHeaders } from "@/api/file";
import { saveAs } from 'file-saver';  
import XLSX from 'xlsx'; 
const defaultContent = {
        name: "",
        address: "",
        header: "",
        tel: "",
        email: "",
        head_technology: "",
        tel_technology: "",
        email_technology: "",
        head_quality: "",
        tel_quality: "",
        email_quality: ""
};
export default {
    components: { Pagination, Treeselect },
    data(){
        return {
            form: {
                name: "",
                address: "",
                header: "",
                tel: "",
                email: "",
                head_technology: "",
                tel_technology: "",
                email_technology: "",
                head_quality: "",
                tel_quality: "",
                email_quality: ""
            },
            currentDept: this.$store.state.user.dept,
            upHeaders: upHeaders(),
            upUrl: upUrl(),
            fileList: [],
            Content: defaultContent,
            typeOptions: [],
            listLoading: false,
            dialogVisible: false,
            saveLoading:false,
            impDialogVisible: false,
            downloadUrl: process.env.VUE_APP_BASE_API,
            listQuery: {
                page: 1,
                page_size: 20,
            },
            tableData: {
                count: 0
            },
            impForm:{
                file:''
              },
            dialogType: "new",
            rule: {
                name: [{ required: true, message: "请输入名称", trigger: "blur" }],
            },
            filterOrgText: "",
            tableHeight: null,
        };
    },
    computed: {},
    watch: {
        filterOrgText(val) {
            this.$refs.tree.filter(val);
        },
    },
    created() {

    },
    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.impForm.file = '';
          this.fileList = [];
          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.$message.success("提交成功");
                    this.getList();
                }else{
                    this.$message.error(res.message);
                    this.saveLoading = false;
                    this.fileList = [];
                }
            })
        },
        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.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;
            getCtAll(this.listQuery).then((response) => {
                console.log(response);
                if (response.data) {
                  this.tableData = response.data;
                }
                this.listLoading = false;
            });
        },
        handleExport() {
            let filename = '实验室联系方式表.xlsx';
            console.log(this.tableData)
            const ws = XLSX.utils.json_to_sheet(this.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;  
        },
        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;
            console.log(this.Content);
            console.log(this.currentDept)
            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 del_contact(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);
                        updateContact(this.Content.id, this.Content).then((response) => {
                        if (response.data) {
                        this.tableData = response.data;
                        }
                        this.listLoading = false;
                        this.dialogVisible = false;
                        this.getTableList();
                });
                    } else {
                        createCt(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>
@/api/contacts