<template>
  <div class="app-container">
    <el-row :gutter="2">
      <el-col :span="12">
        <el-card style=" height:750px">
          <div style="margin-top:10px">
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
          </div>
          <el-table
            v-loading="listLoading"
            :data="tableData.results"
            style="width: 100%;margin-top:10px;"
            border
            stripe
            fit
            highlight-current-row
            max-height="600"
            @row-click="sourceRowClick"
          >
            <el-table-column type="index" width="50" />
            <el-table-column align="left" width="230" label="企业名称">
              <template slot-scope="scope">{{ scope.row.company_name }}</template>
            </el-table-column>
            <el-table-column align="left" label="教育工匠总积分">
              <template slot-scope="scope">{{ scope.row.edu_points }}</template>
            </el-table-column>
            <el-table-column align="left" label="协办大赛总积分">
              <template slot-scope="scope">{{ scope.row.co_sponsor_points }}</template>
            </el-table-column>
            <el-table-column align="left" label="企业图片">
              <template slot-scope="scope"><img
                v-if="scope.row.photo"
                :src="scope.row.photo"
                style="width: 50px; height: 50px; object-fit: cover; border-radius: 5px;"></template>
            </el-table-column>
            <el-table-column align="left" label="企业总积分">
              <template slot-scope="scope">{{ scope.row.edu_points+scope.row.co_sponsor_points }}</template>
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">

                <el-button
                  type="primary"
                  size="small"
                  icon="el-icon-edit"
                  @click="handleEdit(scope)"
                />
                <el-button
                  type="danger"
                  size="small"
                  icon="el-icon-delete"
                  @click="handleDelete(scope)"
                />
              </template>
            </el-table-column>
          </el-table>
          <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑信息':'新增信息'">
            <el-form
              ref="commonForm"
              :model="companydata"
              label-width="120px"
              label-position="right"
            >
              <el-form-item label="企业名称" prop="company_name" style="width: 400px;">
                <el-input v-model="companydata.company_name " placeholder="企业名称" />
              </el-form-item>
              <el-form-item label="教育工匠总积分" prop="edu_points">
                <el-input-number v-model="companydata.edu_points " />
              </el-form-item>
              <el-form-item label="协办大赛总积分" prop="co_sponsor_points">
                <el-input-number v-model="companydata.co_sponsor_points " />
              </el-form-item>
              <el-form-item label="头像" prop="path" >
                    <el-upload
                class="avatar-uploader"
                :headers="upHeaders"
                :action="upUrl"
                accept="image/jpeg, image/gif, image/png, image/bmp"
                :show-file-list="true"
                :on-success="handleImgSuccess"
                :before-upload="beforeImgUpload"
              >
              <img v-if="companydata.path" :src="companydata.path" style="width: 80%;height: auto;display: block;"/>
              <el-button size="small" type="primary" v-else>点击上传</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <tinymce 
                v-if="showEditor" 
                v-model="companydata.remark" 
                :height="400" 
                width="90%"/>
            </el-form-item>
            </el-form>
            <div style="text-align:right;">
              <el-button type="danger" @click="dialogVisible=false">取消</el-button>
              <el-button type="primary" @click="confirmcompany('commonForm')">确认</el-button>
            </div>
          </el-dialog>
          <pagination
            v-show="(tableData.count>0) || 0"
            :total="tableData.count || 0"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.limit"
            @pagination="getList"
          />
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card style="height:750px">
          <div style="margin-top:10px">
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd2">新增</el-button>
          </div>
          <el-table
            v-loading="listLoading"
            :data="tableData2.results"
            style="width: 100%;margin-top:10px;"
            border
            stripe
            fit
            highlight-current-row
            max-height="600"
          >
            <el-table-column type="index" width="50" />
            <el-table-column align="left" label="企业名称">
              <template slot-scope="scope">{{ scope.row.parent_company_name }}</template>
            </el-table-column>
            <el-table-column align="left" label="教育工匠积分">
              <template slot-scope="scope">{{ scope.row.child_edu_points }}</template>
            </el-table-column>
            <el-table-column align="left" label="协办大赛积分">
              <template slot-scope="scope">{{ scope.row.child_co_sponsor_points }}</template>
            </el-table-column>
            <el-table-column align="left" label="创建时间">
              <template slot-scope="scope">{{ scope.row.create_time }}</template>
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">

                <el-button
                  type="danger"
                  size="small"
                  icon="el-icon-delete"
                  @click="handleDelete2(scope)"
                />
              </template>
            </el-table-column>
          </el-table>
          <el-dialog :visible.sync="dialogVisible2" :title="dialogType2==='edit'?'编辑信息':'新增信息'">
            <el-form
              ref="commonForm2"
              :model="childCompy"
              label-width="120px"
              label-position="right"
            >
              <el-form-item label="企业名称" prop="child_edu_points">
                <el-select
                  v-model="childCompy.parent_company "
                  placeholder="请选择企业名称"
                  style="width:400px"
                >
                  <el-option
                    v-for="item in companyOption"
                    :key="item.id"
                    :label="item.company_name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="教育工匠积分" prop="child_edu_points">
                <el-input v-model.number="childCompy.child_edu_points" placeholder="教育工匠积分" />
              </el-form-item>
              <el-form-item label="协办大赛积分" prop="child_co_sponsor_points">
                <el-input v-model.number="childCompy.child_co_sponsor_points" placeholder="协办大赛积分" />
              </el-form-item>
            </el-form>
            <div style="text-align:right;">
              <el-button type="danger" @click="dialogVisible2=false">取消</el-button>
              <el-button type="primary" @click="confirmchild('commonForm2')">确认</el-button>
            </div>
          </el-dialog>
          <pagination
            v-show="(tableData2.count>0) || 0"
            :total="tableData2.count || 0"
            :page.sync="listQuery2.page"
            :limit.sync="listQuery2.limit"
            @pagination="getList2"
          />

        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getCompanyList, createCompany, deleteCompany, updateCompany, getChildcompanyList, createChildcomany, deleteChildcomany, updateChildcomany } from '@/api/cms'
import checkPermission from '@/utils/permission'
import Pagination from '@/components/Pagination'
import Tinymce from '@/components/Tinymce'
import { upUrl } from "@/api/file";
import { genTree, deepClone } from '@/utils'
import { getToken } from "@/utils/auth";

const listQuery = {
  page: 1,
  limit: 20,
  search: ''
}
const listQuery2 = {
  page: 1,
  limit: 20,
  search: ''
}
export default {
  name: 'TinymceDemo',
  components: { Pagination, Tinymce},
  data() {
    return {
      upUrl: upUrl(),
      upHeaders: { Authorization: "JWT " + getToken() },
      listQuery: Object.assign({}, listQuery),
      listQuery2: Object.assign({}, listQuery2),
      tableData: [],
      tableData2: [],
      is_show: true,
      listLoading: true,
      dialogVisible: false,
      dialogType: '',
      dialogType2: '',
      showEditor: true,
      dialogVisible2: false,
      childCompy: {},
      companydata: {},
      companyOption: [],
    }
  },
  computed: {},
  created() {
    this.getList()
    this.getList2()
  },
  methods: {
    checkPermission,
    getList() {
      this.listLoading = true
      getCompanyList(this.listQuery).then((response) => {
        this.tableData = response.data
        this.companyOption = genTree(response.data.results)
        this.listLoading = false
      })
    },
    getList2() {
      this.listLoading = true
      getChildcompanyList(this.listQuery2).then((response) => {
        this.tableData2 = response.data
        this.listLoading = false
      })
    },
    handleImgSuccess(res, file) {
        this.companydata.photo = res.data.path
    },
    beforeImgUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 0.6;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 600KB!");
      }
      return isLt2M;
    },
    handleAdd() {
      this.companydata = {}
      this.dialogType = 'new'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['commonForm'].clearValidate()
      })
    },
    handleAdd2() {
      this.childCompy = {}
      this.dialogType2 = 'new'
      this.dialogVisible2 = true
      this.$nextTick(() => {
        this.$refs['commonForm2'].clearValidate()
      })
    },
    handleEdit(scope) {
      this.showEditor = false
      this.$nextTick(() => {
      this.companydata = JSON.parse(JSON.stringify(scope.row))
      this.showEditor = true
      this.dialogVisible = true
      this.dialogType = 'edit'
      this.$nextTick(() => {
        this.$refs.commonForm && this.$refs.commonForm.clearValidate()
      })
    })
  },

    handleDelete(scope) {
      this.$confirm('确认删数据吗?将丢失数据!', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'error'
      })
        .then(async() => {
          await deleteCompany(scope.row.id)
          this.getList()
          this.$message({
            type: 'success',
            message: '成功删除!'
          })
        })
        // eslint-disable-next-line handle-callback-err
        .catch(err => {
          // console.error(err);
        })
    },
    // 行单击事件
    sourceRowClick(row) {
      this.listQuery2.parent_company = row.id
      this.compayNameC = row.company_name
      this.getList2()
    },
    handleTop(scope) {

    },
   //企业创建
    async confirmcompany(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          const isEdit = this.dialogType === 'edit'
          if (isEdit) {
            updateCompany(this.companydata.id, this.companydata).then(() => {
              this.getList()
              // 清空上传图片
              this.dialogVisible = false
              this.$message.success('成功')
            })
          } else {
            createCompany(this.companydata).then(res => {
              // this.exam = res.data
              // this.tableData.unshift(this.exam)
              this.getList()
              this.dialogVisible = false
              this.$message.success('成功')
            })
          }
        } else {
          return false
        }
      })
    },
    //积分创建
    async confirmchild(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          const isEdit = this.dialogType2 === 'edit'
          if (isEdit) {
            updateCompany(this.childCompy.id, this.childCompy).then(() => {
              this.getList2()
              this.getList()
              this.dialogVisible2 = false
              this.$message.success('成功')
            })
          } else {
            createChildcomany(this.childCompy).then(res => {
              // this.exam = res.data
              // this.tableData.unshift(this.exam)
              this.getList2()
              this.getList()
              this.dialogVisible2 = false
              this.$message.success('成功')
            })
          }
        } else {
          return false
        }
      })
    },
    handleDelete2(scope) {
      this.$confirm('确认删数据吗?将丢失数据!', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'error'
      })
        .then(async() => {
          await deleteChildcomany(scope.row.id)
          this.getList2()
          this.getList()
          this.$message({
            type: 'success',
            message: '成功删除!'
          })
        })
        // eslint-disable-next-line handle-callback-err
        .catch(err => {
          // console.error(err);
        })
    },

  }
}
</script>
