<template>
    <div>
      <el-card class="el-card">
        <el-form  :model="query" label-width="100px" v-if="showSearch" size="mini">
          <el-row>
            <el-col :span="6">
                <el-form-item label="搜索:">
                    <el-input v-model="query.key" placeholder="搜索" style="width: 90%"></el-input>
                </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <div class="top-right-btn">
          <el-button-group style="display:flex;">
            <el-button icon="el-icon-view" type="primary" @click="hideSearch">显示/隐藏搜索栏</el-button>
              <el-button type="primary" icon="el-icon-refresh" @click="onReset">重置</el-button>
              <el-button type="primary" icon="el-icon-search"  @click="getList">查询</el-button>
              <el-button type="primary" icon="el-icon-upload2" @click="selectExport" v-if="selectType==0">选中导出</el-button>
              <el-button type="primary" icon="el-icon-upload2" @click="allExport" v-if="selectType==0">结果全部导出</el-button>
              <el-button type="primary" icon="el-icon-top-upload" @click="uploadSMP" v-if="selectType==1">选中上传</el-button>
              <el-button type="primary" icon="el-icon-top-upload" @click="uploadSMP" v-if="selectType==1">一键上传</el-button>
            </el-button-group>
        </div>

        <el-divider style="margin: 15px"></el-divider>

        <el-table v-loading="loading" :data="list" style="width: 100%" @selection-change="handleSelectionChange" border highlight-current-row>
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="序号" type="index"></el-table-column>
            <el-table-column label="往来单位编码" prop="erpId" show-overflow-tooltip width="100" v-if="erpIdColumn"></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="creditNo" show-overflow-tooltip></el-table-column>
            <el-table-column label="地址" prop="addr" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="60">
                <template slot-scope="scope">
                    <el-button type="text" size="small" @click.native="handleForm(scope.$index, scope.row)">详情</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="query.page"
          :limit.sync="query.limit"
          @pagination="handleCurrentChange"
        ></pagination>

        <!--表单-->
        <el-dialog
            title="往来单位详情"
            :visible.sync="formVisible"
            :before-close="hideForm"
            width="60%"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            append-to-body
        >
            <el-table :data="sysList" style="width: 100%" border highlight-current-row>
                <el-table-column label="序号" type="index"></el-table-column>
                <el-table-column label="第三方系统名称" prop="sysName" show-overflow-tooltip></el-table-column>
                <el-table-column label="第三方往来单位ID" prop="thirdId" show-overflow-tooltip></el-table-column>
                <el-table-column label="第三方往来单位名称" prop="thirdName" show-overflow-tooltip></el-table-column>
            </el-table>

            <el-form :model="formData" :rules="formRules" style="margin-top: 20px" ref="dataForm" label-width="100px">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="往来单位名称:" prop="name">
                    <el-input v-model="formData.name" size="small" style="width: 90%"  @input="change()" splaceholder="请输入往来单位名称"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="往来单位编码:" prop="erpId">
                    <el-input v-model="formData.erpId" style="width: 90%" splaceholder="请输入往来单位编码" auto-complete="off" disabled="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="社会信用号:" prop="creditNo">
                    <el-input v-model="formData.creditNo" style="width: 90%" splaceholder="请输入社会信用号" auto-complete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="联系人:" prop="contact">
                    <el-input v-model="formData.contact" style="width: 90%" splaceholder="请输入联系人" auto-complete="off"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="地址:" prop="addr">
                    <el-input type="" v-model="formData.addr" style="width: 90%" splaceholder="请输入地址" ete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                <el-form-item label="联系电话:" prop="mobile">
                  <el-input v-model="formData.mobile" auto-complete="off" splaceholder="请输入联系电话" style="width: 90%"></el-input>
                </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="拼音码:" prop="spell">
                    <el-input v-model="formData.spell" auto-complete="off" splaceholder="请输入拼音码" style="width: 90%"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
        </el-dialog>
      </el-card>
    </div>
</template>

<script>
import {
  getBasicUnitMaintains,
  basicUnitMaintainSave,
  deleteBasicUnitMaintain, getThrsysUnit, getSystemParamConfig
} from "@/api/basic/basicUnitMaintain";
    import {corpUpload} from "@/api/thrsys/smp"
    import {getBasicThirdSys} from "@/api/basic/basicThirdSys";
    import {exportExcel} from "@/api/basic/corpExport"

    var pinyin = require("pinyin");

    const formJson = {
        id: "",
        thirdId: "",
        erpId: "",
        name: "",
        spell: "",
        addr: "",
        status: "",
        type: "",
        creditNo: "",
        contact: "",
        mobile: ""
    };
    export default {
        name: "CorpInfoSelect",
        props: {
            selectType: {
                type: Object,
                required: true,
            },
        },

        data() {
            return {
              showSearch: true,
                query: {
                    ids: [],
                    key: "",
                    page: 1,
                    limit: 20,
                },
                erpIdColumn: false,
                thirdIdColumn: false,
                editQuery: null,
                corpData: null,
                checked: false,
                formName: null,
                formMap: {
                    add: "新增",
                    update: "编辑"
                },
                formLoading: false,
                formVisible: false,
                formData: formJson,
                combinType: 0,//0:新增，1，修改
                combinTypeMap: {
                    0: "选入往来单位信息",
                    1: "关联往来单位信息",
                },
                formRules: {},
                spellUpdate: false,
                editDialogVisible: false,
                selectDrugDialogVisible: false,
                selectSingleUnitVisible: false,
                list: [],
                sysList: [],
                total: 0,
                multipleSelection: [],
                thirdSys: [],
                thirdSysFk: null,
            };
        },

        methods: {
            onReset() {
                this.$router.push({
                    path: "",
                });
                this.query = {
                    key: "",
                    page: 1,
                    limit: 20,
                };
                this.getList();
            },
          hideSearch() {
            this.showSearch = !this.showSearch;
          },
            getList() {
                this.loading = true;
                this.erpIdColumn = false;
                this.thirdIdColumn = false;
                getBasicUnitMaintains(this.query)
                    .then((response) => {
                        console.log(response)
                        this.loading = false;
                        this.getSystemParamConfig();
                        this.list = response.data.list || [];
                        console.log(this.list)
                        this.total = response.data.total || 0;
                        console.log(this.total)
                    })
                    .catch(() => {
                        this.loading = false;
                        this.list = [];
                        this.total = 0;
                    });
            },
            // 刷新表单
            resetForm() {
                if (this.$refs["dataForm"]) {
                    // 清空验证信息表单
                    this.$refs["dataForm"].clearValidate();
                    // 刷新表单
                    this.$refs["dataForm"].resetFields();
                    this.getList();
                }
            },
            // 隐藏表单
            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";
                this.spellUpdate = false;
                if (index !== null) {
                    this.index = index;
                    this.formName = "update";
                    this.spellUpdate = true;
                }
                this.editQuery = row;
                this.getThirdSysDetail();
            },
            formSubmit() {
                this.$refs["dataForm"].validate(valid => {
                    if (valid) {
                        this.formLoading = true;
                        let data = Object.assign({}, this.formData);

                        // if (!this.spellUpdate) {
                        //     var py = pinyin(data.name.trim(), {
                        //         style: pinyin.STYLE_FIRST_LETTER, // 设置拼音风格
                        //         heteronym: true
                        //     });
                        //     var pyStr = py.join('');
                        //     data.spell = pyStr.toUpperCase();
                        // }

                        console.log('------2------');
                        basicUnitMaintainSave(data, this.formName)
                            .then(response => {
                                this.formLoading = false;
                                if (response.code !== 20000) {
                                    this.$message.error(response.message);
                                    return false;
                                }
                                this.$message.success("操作成功");
                                this.formVisible = false;
                                if (this.formName === "add") {
                                    // 向头部添加数据
                                    if (response.data && response.data.id) {
                                        data.id = response.data.id;
                                        this.list.unshift(data);
                                    }
                                } else {
                                    this.list.splice(this.index, 1, data);
                                }
                                // 刷新表单
                                this.resetForm();
                                this.getList();
                            })
                            .catch(() => {
                                this.formLoading = false;
                            });
                    }
                });
            },
            change() {
                var pinyin = require("pinyin");
                var py = pinyin(this.formData.name, {
                    style: pinyin.STYLE_FIRST_LETTER, // 设置拼音风格
                    heteronym: true,
                });
                var str = "";
                py.forEach((item) => {
                    str = str + item[0];
                });
                this.formData.spell = str;
            },

            deleteUnit(data) {
                this.loading = true;
                let tquery = {
                    id: data.id + "",
                };

                deleteBasicUnitMaintain(tquery)
                    .then((response) => {
                        if (response.code == 20000) {
                            this.getList();
                            this.$message({
                                type: "success",
                                message: "删除成功！",
                            });
                        } else {
                            this.$message.error(response.message);
                        }

                    })
                    .catch(() => {
                    });
            },

            cancelDialog() {
                this.editDialogVisible = false;
                this.selectSingleUnitVisible = false;
                this.getList();
            },
            closeMain(val) {
                this.selectDrugDialogVisible = false;

                if (val) {
                    this.$message.success("添加成功！");
                    this.getList();
                } else {
                    this.$message.error("添加失败！");
                }
            },

            selectExport() {
                var selectData = this.multipleSelection;
                selectData.forEach((obj) => {
                    this.query.ids.push(obj.id);
                });
              exportExcel(this.query)
                .then((response) => {
                  if (response.code == 20000) {
                    this.$message({
                      type: "success",
                      message: "导出成功，后台正在生成Json文件，请稍后刷新查看！",
                    });
                  } else {
                    this.$message({
                      type: "error",
                      message: response.message,
                    });
                  }
                  this.$emit("cancelDialog", true);
                })
                .catch(() => {
                  this.$message({
                    type: "error",
                    message: "上传失败",
                  });
                });
            },
            allExport() {
                this.query.limit = this.total;
                getBasicUnitMaintains(this.query)
                  .then((response) => {
                    this.list = response.data.list || [];
                    console.log(this.list)
                    this.total = response.data.total || 0;
                    var selectData = this.list;
                    selectData.forEach((obj) => {
                      this.query.ids.push(obj.id);
                    });
                    exportExcel(this.query)
                      .then((response) => {
                        if (response.code == 20000) {
                          this.$message({
                            type: "success",
                            message: "导出成功，后台正在生成Json文件，请稍后刷新查看！",
                          });
                        } else {
                          this.$message({
                            type: "error",
                            message: response.message,
                          });
                        }
                        this.$emit("cancelDialog", true);
                      })
                      .catch(() => {
                        this.$message({
                          type: "error",
                          message: "上传失败",
                        });
                      });
                  })
                  .catch(() => {
                    this.loading = false;
                    this.list = [];
                    this.total = 0;
                  });
            },

            uploadSMP() {
                var selectData = this.multipleSelection;
                selectData.forEach((obj) => {
                    this.query.ids.push(obj.id);
                });
                this.allUploadSMP();
            },

            allUploadSMP() {
                corpUpload(this.query)
                    .then((response) => {
                        if (response.code == 20000) {
                            this.$message.success("提交成功，后台正在上传！")
                        } else {
                            this.$message.error(response.message)
                        }
                        this.$emit("cancelDialog", true);
                    })
                    .catch(() => {
                        this.$message.error("上传失败！");
                    });
            },

            handleModifyClick(row) {
                this.editDialogVisible = true;
                this.editQuery = row;
                this.getThirdSysDetail();
            },

            deleteDialog(rowId) {
                this.$confirm("此操作将永久删除该往来单位信息, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(() => {
                        this.deleteUnit(rowId);
                    })
                    .catch(() => {
                    });
            },

            intentDetail() {
                this.combinType = 0;
                this.selectDrugDialogVisible = true;
            },

            intentSelect(row) {
                this.combinType = 1;
                this.corpData = row;
                this.selectSingleUnitVisible = true;
            },

            handleSelectionChange(val) {
                this.multipleSelection = val;
            },

            handleCurrentChange(val) {
                this.query.page = val.page;
                this.getList();
            },
            getBasicThirdSys() {
                let query = {
                    enabled: null,
                };
                getBasicThirdSys(query)
                    .then((response) => {
                        this.thirdSys = response.data.list || [];
                        this.thirdSysFk = this.thirdSys[0].thirdId;
                    })
                    .catch(() => {
                        this.loading = false;
                        this.list = [];
                    });
            },
          getSystemParamConfig(){
            getSystemParamConfig().then((req) => {
              this.erpIdColumn = req.data.BUMErpIdValue == "1" ? true : false;
              this.thirdIdColumn = req.data.BUMThirdIdValue == "1" ? true : false;
            })
          },
            getThirdSysDetail() {
                let query = {
                    id: this.editQuery.id,
                };

                getThrsysUnit(query)
                    .then((response) => {
                        this.loading = false;
                        this.sysList = response.data.list || [];
                    })
                    .catch(() => {
                        this.loading = false;
                        this.sysList = [];
                    });
            },
        }
        ,
        mounted() {
        }
        ,
        components: {}
        ,
        created() {
            this.getList();
            this.getBasicThirdSys();

        }
        ,
    }
    ;
</script>
<style scoped>
    .itemTag {
        float: left;
        text-align: left;
        margin-top: 10px;
    }

    .text {
        font-size: 13px;
        font-family: "Microsoft YaHei";
    }

    .el-row {
        display: flex;
        flex-wrap: wrap;
    }

    .el-col {
        border-radius: 4px;
        flex-wrap: wrap;
    }


</style>
