<template>
  <div class="table-container">
    <vab-query-form>
      <vab-query-form-left-panel>
        <el-form
          ref="searchForm"
          :model="searchForm"
          :inline="true"
          @submit.native.prevent>
          <el-form-item>
            <el-input v-model="searchForm.name" placeholder="公司名称" />
          </el-form-item>

          <el-form-item>
            <el-input v-model="searchForm.code" placeholder="公司编码" />
          </el-form-item>

          <el-form-item>
            <el-button
              icon="el-icon-search"
              type="primary"
              native-type="submit"
              @click="handleQuery"
            >
              查询
            </el-button>
            <el-button icon="el-icon-plus" type="primary" @click="handleAdd">
              添加
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-left-panel>
    </vab-query-form>

    <el-table
      ref="tableSort"
      v-loading="listLoading"
      :data="tableData"
      :element-loading-text="elementLoadingText"
      :height="height"
      :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }"
    >
      >

      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="鉴权URL:">
              <span>{{ props.row.comUrl }}</span>
            </el-form-item>
            <el-form-item label="推送数据URL:">
              <span>{{ props.row.pushUrl }}</span>
            </el-form-item>
            <el-form-item label="拉取数据URL:">
              <span>{{ props.row.pullUrl }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column show-overflow-tooltip label="序号" width="95">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="name" label="公司名称" />
      <el-table-column show-overflow-tooltip label="公司编码" prop="code" />

      <el-table-column show-overflow-tooltip label="联系方式" prop="contact" />

      <el-table-column show-overflow-tooltip label="操作" width="180px">
        <template #default="{ row }">
          <el-button type="text" @click="handleEdit(row)">
            <el-tag type="success">编辑</el-tag>
          </el-button>
          <el-button type="text" @click="handleDelete(row)">
            <el-tag type="danger">删除</el-tag>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :background="background"
      :current-page="page.currentPage"
      :layout="layout"
      :page-size="page.pageSize"
      :total="page.total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    ></el-pagination>

    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      width="500px"
      @close="close"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="公司名称" prop="name">
          <el-input v-model.trim="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="公司编码" prop="code">
          <el-input v-model.trim="form.code" autocomplete="off" :disabled="isEdit"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model.trim="form.contact" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="鉴权URL" prop="username">
          <el-input v-model.trim="form.comUrl" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="推送数据URL" prop="username">
          <el-input v-model.trim="form.pushUrl" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="拉取数据URL" prop="username">
          <el-input v-model.trim="form.pullUrl" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdate()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    fetchList,
    addObj,
    putObj,
    delObj,
    getObj,
  } from '@/api/integrationCompany'

  export default {
    name: 'InCompany',

    data() {
      const validateInCompanyCode = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请输入一体化公司编码'))
        }
        getObj(this.form.code, value).then((response) => {
          if (this.dialogType === 'edit') callback()
          let result = response.data
          if (result !== null) {
            callback(new Error('一体化公司编码已存在'))
          } else {
            callback()
          }
        })
      }

      return {
        isEdit: false,
        dialogFormVisible: false,
        dialogType: '',
        title: '',
        tableData: [],
        companys: [],
        elType: [
          { label: '光电', value: 'E1' },
          { label: '风电', value: 'E2' },
        ],
        searchForm: {
          code: null,
          name: null,
        },
        form: {},
        imgShow: true,
        list: [],
        imageList: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        background: true,
        selectRows: '',
        elementLoadingText: '正在加载...',
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20, // 每页显示多少条
        },
        rules: {
          name: [
            { required: true, trigger: 'blur', message: '请输入公司名称' },
          ],

          code: [
            {
              required: true,
              trigger: 'blur',
              validator: validateInCompanyCode,
            },
          ],
        },
      }
    },
    computed: {
      height() {
        return this.$baseTableHeight()
      },
    },
    created() {
      this.fetchData()
    },
    methods: {
      async fetchData() {
        this.listLoading = true
        fetchList(
          Object.assign(
            {
              current: this.page.currentPage,
              size: this.page.pageSize,
            },
            this.searchForm
          )
        )
          .then((response) => {
            this.tableData = response.data.records
            this.page.total = response.data.total
            this.listLoading = false
          })
          .catch(() => {
            this.listLoading = false
          })
      },

      handleSizeChange(val) {
        this.page.pageSize = val
        this.page.currentPage = 1
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.page.currentPage = val
        this.fetchData()
      },
      handleQuery() {
        for (var v in this.searchForm) {
          if (this.searchForm[v] == '') {
            delete this.searchForm[v]
          }
        }

        this.page.currentPage = 1
        this.fetchData()
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
        this.$emit('fetch-data')
      },
      handleAdd() {
        this.isEdit = false
        this.form = {}
        this.title = '新增'
        this.dialogType = 'add'
        this.dialogFormVisible = true
      },
      handleEdit(row) {
        this.isEdit = true
        var newObj = JSON.parse(JSON.stringify(row))
        this.form = newObj
        this.title = '修改'
        this.dialogType = 'edit'
        this.dialogFormVisible = true
      },
      handleDelete(row) {
        this.$baseConfirm('你确定要删除当前项吗', null, async () => {
          const { msg } = await delObj(row.id)
          this.$baseMessage(msg, 'success')
          this.fetchData()
        })
      },
      saveOrUpdate() {
        if (this.dialogType == 'add') {
          this.save()
        } else {
          this.update()
        }
      },
      save() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.listLoading = true
            addObj(this.form)
              .then((response) => {
                this.dialogFormVisible = false
                this.fetchData()
                this.listLoading = false
              })
              .catch(() => {
                this.listLoading = false
              })
          } else {
            return false
          }
        })
      },
      update() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.listLoading = true
            putObj(this.form)
              .then((response) => {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                });
                this.dialogFormVisible = false
                this.fetchData()
                this.listLoading = false
              })
              .catch(() => {
                this.$message({
                  message: '修改失败',
                  type: 'warning'
                });
                this.listLoading = false
              })
          } else {
            return false
          }
        })
      },
    },
  }
</script>

<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
