<template>
  <div>
    <el-form :inline="true" :model="query" class="query-form" size="mini">
      <el-row>
        <el-form-item class="query-form-item">
          <el-input v-model="query.key" placeholder="搜索"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button-group>
            <el-button
              type="primary"
              icon="el-icon-refresh"
              @click="onReset"
            ></el-button>
            <el-button type="primary" icon="search" @click="getList"
              >查询</el-button
            >
            <el-button @click="deleteDialog" size="mini" type="primary"
              >导入TXT往来单位信息</el-button
            >
          </el-button-group>
        </el-form-item>
      </el-row>
    </el-form>

    <el-table v-loading="loading" :data="list" style="width: 100%">
      <el-table-column label="往来单位ID" prop="unitId" show-overflow-tooltip></el-table-column>
      <el-table-column label="往来单位名称" prop="name" show-overflow-tooltip></el-table-column>
      <el-table-column
        label="往来单位简写"
        prop="spell"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="地址" prop="addr" show-overflow-tooltip></el-table-column>
      <el-table-column label="联系方式" prop="status" show-overflow-tooltip></el-table-column>
      <el-table-column label="类型" prop="type" show-overflow-tooltip></el-table-column>
    </el-table>

    <el-pagination
      :page-size="query.limit"
      @current-change="handleCurrentChange"
      layout="prev, pager, next"
      :total="total"
    ></el-pagination>

    <el-upload multiple :limit="1" :on-change="loadUnitFile">
      <button id="initSlide" style="width: 0%; height: 0.1px"></button>
    </el-upload>
  </div>
</template>

<script>
import { saveUnits, unitList, unitListBykey } from "../../api/warehouse/unit";
import draggable from "vuedraggable";
import { saveAs } from "file-saver";
const formJson = {
    unitId: "",
    name: "",
    spell: "",
    addr: "",
    status: "",
    type: ""
};

export default {
    data() {
        return {
            query: { key: "", page: 1, limit: 20 },
            addQuery: {
                unitList: null
            },
            list: [],
            adListNoDataText: "无数据",
            queryAdIdAsyncLoading: false,
            total: 0,
            loading: true,
            index: null,
            formName: null,
            formMap: {
                add: "新增",
                edit: "编辑"
            },
            checked: false,
            formLoading: false,
            formVisible: false,
            formData: formJson,
            time: 0,
            deleteLoading: false
        };
    },
    components: {
        draggable
    },
    methods: {
        onReset() {
            this.$router.push({
                path: ""
            });
            this.query = {
                key: "",
                page: 1,
                limit: 20
            };
            this.getList();
        },
        onSubmit() {
            this.$router.push({
                path: "",
                query: this.query
            });
            this.getList();
        },
        handleSizeChange(val) {
            this.query.limit = val;
            this.getList();
        },
        handleCurrentChange(val) {
            this.query.page = val;
            this.getList();
        },

        readFile(file) {
            return new Promise(function(resolve, reject) {
                let reader = new FileReader();
                // console.log(fileselect);
                if (typeof FileReader === "undefined") {
                    alert("您的浏览器不支持FileReader接口");
                }
                reader.readAsText(file.raw, "utf-8"); //注意读取中文的是用这个编码，不是utf-8  gb2312
                var fileContent;
                var uploadData = [];

                reader.onload = function() {
                    fileContent = reader.result;
                    var data = fileContent.split("\n");
                    var form = this.formData;
                    data.forEach(function(value, index, array) {
                        var subData = value.split(",");
                        var uploadSubData = Object.assign({}, form);
                        uploadSubData.unitId = subData[2];
                        uploadSubData.name = subData[0];
                        uploadSubData.spell = subData[1];
                        uploadSubData.addr = subData[3];
                        uploadSubData.status = subData[4];
                        uploadSubData.type = subData[5];
                        uploadData[index] = uploadSubData;
                    });
                    resolve(uploadData);
                };
            });
        },
        deleteDialog() {
            this.$confirm("导入数据会覆盖现有往来单位信息！", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    var e = document.createEvent("MouseEvents");
                    e.initEvent("click", true, true);
                    document.getElementById("initSlide").dispatchEvent(e);
                })
                .catch(() => {});
        },
        loadUnitFile(file) {
            let temp = new Date().getTime();
            if (temp - this.time > 3 * 1000) {
                this.loading = true;
                this.time = temp;
                console.log("importFile=" + file);
                this.readFile(file).then(result => {
                    console.log("result=" + result);
                    // this.loading = true;
                    // addQuery.unitList = resuly;
                    let tquery = {
                        unitList: result
                    };
                    saveUnits(tquery).then(response => {
                        this.loading = false;
                        this.$message.success("导入成功");
                        this.getList();
                    });
                });
            }
        },

        //获取订单列表
        getList() {
            this.loading = true;
            unitListBykey(this.query)
                .then(response => {
                    this.loading = false;
                    this.list = response.data.list || [];
                    this.total = response.data.total || 0;
                })
                .catch(() => {
                    this.loading = false;
                    this.list = [];
                    this.total = 0;
                });
        },

        // 刷新表单
        resetForm() {
            if (this.$refs["dataForm"]) {
                // 清空验证信息表单
                this.$refs["dataForm"].clearValidate();
                // 刷新表单
                this.$refs["dataForm"].resetFields();
            }
        },
        // 隐藏表单
        hideForm() {
            // 更改值
            this.formVisible = !this.formVisible;
            return true;
        },
        // 显示表单
        handleForm(index, row) {
            this.formVisible = true;
            this.formData = JSON.parse(JSON.stringify(formJson));
            if (row !== null) {
                this.formData = Object.assign({}, row);
            }
            this.formName = "add";
            if (index !== null) {
                this.index = index;
                this.formName = "edit";
            }
        },
        formSubmit() {
            this.$refs["dataForm"].validate(valid => {
                if (valid) {
                    this.formLoading = true;
                    let data = Object.assign({}, this.formData);
                    let ad_ids = [];
                    let ads = data.ads;
                    ads.forEach(function(value) {
                        ad_ids.push(value.ad_id);
                    });
                    data.ads = [];
                    data.ad_ids = ad_ids;
                    let addData = Object.assign({}, this.formData);
                    adSiteSave(data, this.formName)
                        .then(response => {
                            this.formLoading = false;
                            if (response.code) {
                                this.$message.error(response.message);
                                return false;
                            }
                            this.$message.success("操作成功");
                            this.formVisible = false;
                            if (this.formName === "add") {
                                // 向头部添加数据
                                addData.site_id = response.data.site_id;
                                this.list.unshift(addData);
                            } else {
                                this.list.splice(this.index, 1, addData);
                            }
                            // 刷新表单
                            this.resetForm();
                        })
                        .catch(() => {
                            this.formLoading = false;
                        });
                }
            });
        }
        // 删除
    },
    filters: {},
    mounted() {
        document.body.ondrop = function(event) {
            event.preventDefault();
            event.stopPropagation();
        };
    },
    created() {
        // 将参数拷贝进查询对象
        let query = this.$route.query;
        this.query = Object.assign(this.query, query);
        this.query.limit = parseInt(this.query.limit);
        // 加载表格数据
        this.getList();
    }
};
</script>

<style type="text/scss" lang="scss">
</style>
