<template>
  <div>
    <el-card class="el-card">
      <el-form :model="query" label-width="100px" class="query-form" size="mini" v-if="showSearch">
        <el-row>
          <el-col span="6">
            <el-form-item label="搜索:">
              <el-input v-model="query.key" placeholder="搜索" style="width: 90%" clearable="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col span="6">
            <el-form-item label="往来单位类型:">
              <el-select v-model="query.corpType" style="width: 90%" placeholder="请选择往来单位类型">
                <el-option label="全部" value=""></el-option>
                <el-option label="客户" value="1"></el-option>
                <el-option label="供应商" value="2"></el-option>
                <el-option label="内部科室" value="3"></el-option>
                <!--                <el-option label="特殊科室" value="3"></el-option>-->
                <el-option label="特殊往来" value="4"></el-option>
              </el-select>
            </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="search">查询</el-button>
          <el-button type="primary" icon="el-icon-plus" @click.native="handleForm(null, null)"
                     :disabled="!configParms.basicCorp" >新增
          </el-button>
          <el-button type="primary" icon="el-icon-bottom-right" @click="intentDetail">选入往来单位信息</el-button>
        </el-button-group>
      </div>
      <el-divider style="margin: 15px"></el-divider>


      <el-table v-loading="loading" :data="list" style="width: 100%" border highlight-current-row
                @selection-change="handleSelectionChange">
        <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></el-table-column>
        <el-table-column label="第三方主系统ID" prop="thirdId" 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="creditNo" show-overflow-tooltip></el-table-column>
        <el-table-column label="地址" prop="addr" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button type="text" @click.native="handleForm(scope.$index, scope.row)">编辑</el-button>
            <el-button type="text" :disabled="!configParms.basicCorp" @click.native.stop="deleteDialog(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="combinTypeMap[combinType]"
        :visible.sync="selectDrugDialogVisible"
        width="80%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        v-if="selectDrugDialogVisible"
      >
        <selectUnit v-on:closeMain="closeMain"></selectUnit>
      </el-dialog>

      <el-dialog
        :title="combinTypeMap[combinType]"
        :visible.sync="selectSingleUnitVisible"
        width="85%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        v-if="selectSingleUnitVisible"
      >
        <selectSingleUnit v-on:cancelDialog="cancelDialog" :corpData="corpData"
                          :defaultSys="defaultSys"></selectSingleUnit>
      </el-dialog>


      <!--表单-->
      <el-dialog
        :title="formMap[formName]"
        :visible.sync="formVisible"
        :before-close="hideForm"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        width="60%"
        top="5vh"
      >
        <el-table :data="sysList" style="width: 100%" border v-if="formName=='update'">
          <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-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="intentSelect(scope.row)" :disabled="!configParms.basicCorp">
                关联
              </el-button>
              <el-button type="text" size="small" @click.native.stop="removeErp(scope.row)"
                         :disabled="scope.row.thirdId=='' ||scope.row.thirdId==null || !configParms.basicCorp">解绑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-form :model="editQuery" :rules="formRules" style="margin-top: 20px" label-width="120px" ref="dataForm">
          <el-row type="flex">
            <el-col :span="12" type="flex">
              <el-form-item label="往来单位名称" prop="name">
                <el-input v-model="editQuery.name" size="small" style="width: 90%" auto-complete="off" @input="change()"
                          splaceholder="请输入往来单位名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" type="flex">
              <el-form-item label="往来单位编码" prop="erpId">
                <el-input v-model="editQuery.erpId" style="width: 90%" auto-complete="off" disabled="true"
                          splaceholder="请输入往来单位编码"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex">
            <el-col :span="12" type="flex">
              <el-form-item label="社会信用号" prop="creditNo">
                <el-input v-model="editQuery.creditNo" style="width: 90%" splaceholder="请输入社会信用号"
                          auto-complete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" type="flex">
              <el-form-item label="联系人" prop="contact">
                <el-input v-model="editQuery.contact" splaceholder="请输入联系人" style="width: 90%"
                          auto-complete="off"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :type="flex">
            <el-col :span="12" type="flex">
              <el-form-item label="地址" prop="addr">
                <el-input type="" v-model="editQuery.addr" splaceholder="请输入地址" style="width: 90%"
                          auto-complete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" type="flex">
              <el-form-item label="联系电话" prop="mobile">
                <el-input v-model="editQuery.mobile" splaceholder="请输入联系电话" auto-complete="off"
                          style="width: 90%"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :type="flex">
            <el-col :span="12" type="flex">
              <el-form-item label="往来单位类型" prop="corpType">
                <el-select v-model="editQuery.corpType" style="width: 90%" placeholder="请选择往来单位类型">
                  <el-option
                    v-for="item in corpTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" type="flex">
              <el-form-item label="拼音码" prop="spell">
                <el-input v-model="editQuery.spell" placeholder="请输入拼音码" auto-complete="off"
                          style="width: 90%"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style='text-align: center; margin-bottom: 10px;'>
          <el-button @click.native="hideForm">取消</el-button>
          <el-button type="primary" @click.native="formSubmit()" :loading="formLoading"
                     :disabled="!configParms.basicCorp">提交
          </el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  getBasicUnitMaintains,
  basicUnitMaintainSave,
  deleteBasicUnitMaintain,
  getThrsysUnit,
  removeRl,
  getSystemParamConfig
} from "@/api/basic/basicUnitMaintain";
import selectUnit from "./corpRelevance";
import selectSingleUnit from "./corpSingleRelevance";
import {getBasicThirdSys} from "@/api/basic/basicThirdSys";
import {findConfig} from "@/api/sync/spsSyncStatus";

var pinyin = require("pinyin");

export default {
  data() {
    return {
      query: {
        key: "",
        corpType: "2",
        page: 1,
        limit: 20,
      },
      showSearch: true,
      erpIdColumn: false,
      thirdIdColumn: false,
      editQuery: {
        id: "",
        thirdId: "",
        erpId: "",
        name: "",
        spell: "",
        addr: "",
        status: "",
        type: "",
        creditNo: "",
        contact: "",
        mobile: ""
      },
      corpData: null,
      checked: false,
      formName: null,
      formMap: {
        add: "新增",
        update: "编辑"
      },
      formLoading: false,
      formVisible: false,
      combinType: 0,//0:新增，1，修改
      combinTypeMap: {
        0: "选入往来单位信息",
        1: "关联往来单位信息",
      },

      corpTypeList: [
        {
          value: 1,
          label: "客户"
        },
        {
          value: 2,
          label: "供应商"
        },
        {
          value: 3,
          // label: "特殊科室"
          label: "内部科室"
        },
        {
          value: 4,
          label: "特殊往来"
        }

      ],
      formRules: {
        name: [
          {required: true, message: "请输入名称", trigger: "blur"}
        ],
        // erpId: [
        //     {required: true, message: "请输入自定义码", trigger: "blur"}
        // ],
        creditNo: [
          {required: true, message: "请输入社会信用号", trigger: "blur"}
        ],
        corpType: [
          {required: true, message: "请选择往来单位类型", trigger: "blur"}
        ]
      },
      spellUpdate: false,
      editDialogVisible: false,
      selectDrugDialogVisible: false,
      selectSingleUnitVisible: false,
      list: [],
      sysList: [],
      loading: false,
      total: 0,
      multipleSelection: [],
      thirdSys: [],
      thirdSysFk: null,
      defaultSys: null,
      configParms: {},
    };
  },

  methods: {
    onReset() {
      this.$router.push({
        path: "",
      });
      this.query = {
        key: "",
        corpType: "2",
        page: 1,
        limit: 20,
      };
      this.getList();
    },
    search() {
      this.query.page = 1;
      this.getList();
    },
    getList() {
      this.loading = true;
      this.erpIdColumn = false;
      this.thirdIdColumn = false;
      getBasicUnitMaintains(this.query)
        .then((response) => {
          this.getSystemParamConfig();
          this.loading = false;
          this.list = response.data.list || [];
          this.total = response.data.total || 0;
        })
        .catch(() => {
          this.loading = false;
          this.list = [];
          this.total = 0;
        });
    },
    getSystemParamConfig() {
      getSystemParamConfig().then((req) => {
        this.erpIdColumn = req.data.BUMErpIdValue == "1" ? true : false;
        this.thirdIdColumn = req.data.BUMThirdIdValue == "1" ? true : false;
      })
    },
    hideSearch() {
      this.showSearch = !this.showSearch;
    },
    // 刷新表单
    resetForm() {
      if (this.$refs["dataForm"]) {
        // 清空验证信息表单
        this.$refs["dataForm"].clearValidate();
        // 刷新表单
        this.$refs["dataForm"].resetFields();
        this.getList();
      }
    },
    // 隐藏表单
    hideForm() {
      // 更改值
      this.formVisible = !this.formVisible;
      this.getList();
      return true;
    },
    // 显示表单
    handleForm(index, row) {
      this.formVisible = true;
      this.formName = "add";
      this.spellUpdate = false;
      if (index !== null) {
        this.index = index;
        this.formName = "update";
        this.spellUpdate = true;
        this.editQuery = row;

      } else {
        this.editQuery = {
          id: "",
          thirdId: "",
          erpId: "",
          name: "",
          spell: "",
          addr: "",
          status: "",
          type: "",
          creditNo: "",
          contact: "",
          mobile: ""
        };
      }

      this.getThirdSysDetail();
    },
    formSubmit() {
      if (this.$isBlank(this.editQuery.corpType)) {
        this.$message.error("往来单位类型不能为空！");
        return;
      }

      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.formLoading = true;
          this.editQuery.thirdId = null;
          this.editQuery.thirdId1 = null;
          this.editQuery.thirdId2 = null;
          this.editQuery.thirdId3 = null;
          this.editQuery.thirdId4 = null;
          this.editQuery.thirdName = null;
          this.editQuery.thirdName1 = null;
          this.editQuery.thirdName2 = null;
          this.editQuery.thirdName3 = null;
          this.editQuery.thirdName4 = null;
          let data = Object.assign({}, this.editQuery);

          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();
            })
            .catch(() => {
              this.formLoading = false;
            });
        }
      });
    },

    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();
      this.getThirdSysDetail();
    },
    closeMain(val) {
      this.selectDrugDialogVisible = false;

      if (val) {
        this.$message.success("添加成功！");
        this.getList();
      } else {
        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(() => {
        });
    },

    exportTxt() {
    },

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

    intentSelect(row) {
      this.combinType = 1;
      this.corpData = this.editQuery;
      this.defaultSys = row.sysId;
      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 = [];
        });
    },

    getThirdSysDetail() {
      let query = {};
      if (this.formName == "update") {
        query = {
          id: this.editQuery.id,
        }
      }
      getThrsysUnit(query)
        .then((response) => {
          this.loading = false;
          this.sysList = response.data.list || [];
        })
        .catch(() => {
          this.loading = false;
          this.sysList = [];
        });
    },

    change() {
      var pinyin = require("pinyin");
      var py = pinyin(this.editQuery.name, {
        style: pinyin.STYLE_FIRST_LETTER, // 设置拼音风格
        heteronym: true,
      });
      var str = "";
      py.forEach((item) => {
        str = str + item[0];
      });
      this.editQuery.spell = str;
    },
    removeErp(row) {
      this.$confirm("此操作将解除该绑定往来单位信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let query = {
            relId: this.editQuery.id,
            thirdSys: row.sysId
          };
          removeRl(query)
            .then((response) => {
              if (response.code == 20000) {
                this.getThirdSysDetail()();
                this.$message({
                  type: "success",
                  message: "解绑成功！",
                });
              } else {
                this.$message.error(response.message);
              }
            })
            .catch(() => {
            });
        })
        .catch(() => {
        });
    },
    getSyncConfig() {
      findConfig()
        .then((response) => {
          if (response.code == 20000) {
            this.configParms = response.data;
          }
        })
        .catch(() => {
        });
    },
  }
  ,
  mounted() {
  }
  ,
  components: {
    selectUnit, selectSingleUnit
  }
  ,
  created() {
    this.getList();
    this.getSyncConfig();
    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>
