<template>
  <div class="info">
    <div>
      <p>基本信息</p>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
        <el-form-item label="企业名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入企业名称"></el-input>
        </el-form-item>
        <el-form-item label="排序：" prop="sort">
          <el-input v-model="ruleForm.sort" placeholder="数字越大越靠前" type="number"></el-input>
        </el-form-item>
        <el-form-item v-for="(item, i) in categoryList" :key="i" :label="item.name" :prop="item.mark">
          <!-- <el-select v-model="ruleForm[item.mark]" :placeholder="'请选择' + item.name" :ref="'template_' + i"
            :style="{ width: '300px' }" filterable clearableruleFormruleForm
            @visible-change="(v) => visibleChange(v, `template_${i}`, item.id)"> -->
          <el-select v-model="ruleForm[item.mark]" :placeholder="'请选择' + item.name" :ref="'template_' + i"
            :style="{ width: '300px' }" filterable clearableruleFormruleForm>
            <el-option v-for="(temp, idx) in item.children" :key="idx" :label="temp.name" :value="temp.id">
              <span style="float: left" class="span-style">{{ temp.name }}</span>
              <!-- <span style="float: right" class="span-style-delete" @click.stop="deleteItem(temp)">
                <i class="el-icon-delete" /></span> -->
              <span style="float: right" class="span-style" @click.stop="editItem(item.id, 1, temp, i)">
                <i class="el-icon-edit-outline" />
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否龙头企业" prop="is_leading" required>
          <el-radio-group v-model="ruleForm.is_leading">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否第三方机构" prop="is_service" required>
          <el-radio-group v-model="ruleForm.is_service">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否研发机构" prop="is_research" required>
          <el-radio-group v-model="ruleForm.is_research">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="企业图片：">
          <el-upload ref="bannerUpload" multiple :limit="15" action="" :show-file-list="false"
            :http-request="bannerPictureUpload">
            <el-button size="mini">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              (建议尺寸画布600*480，大小50K)
            </div>
          </el-upload>
          <div class="flexS" style="flex-wrap: wrap;" v-if="ruleForm.img&&ruleForm.img.length > 0">
            <div v-for="(item, i) in ruleForm.img" :key="i" class="banner_item">
              <el-image :src="item" style="width: 100px;height: 100px;margin:0 10px 0 10px;"
                :preview-src-list="ruleForm.img" />
              <i class="el-icon-delete" @click="deleteBanner(i)" /></span>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="服务案例" prop="service_info" required>
          <textarea name="" id="" cols="30" rows="10" v-model="ruleForm.service_info" style="width:60%;"></textarea>
        </el-form-item>
        <el-form-item label="企业简介" prop="introduction" required>
          <tinymce v-model="ruleForm.introduction" :height="300" width="60%" menubar="" />
        </el-form-item>
        <el-form-item label="企业荣誉" prop="honor" required>
          <tinymce v-model="ruleForm.honor" :height="300" width="60%" menubar="" />
        </el-form-item>
        <el-form-item label="研究成果" prop="achievement" required>
          <tinymce v-model="ruleForm.achievement" :height="300" width="60%" menubar="" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">{{ id ? '保存' : '立即创建' }}</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import Tinymce from '@/components/Tinymce'
import { addCompany, companyCategory, companyInfo, editCompany } from '@/api/company'
import { addCategory, editCategory, deleteCategory } from '@/api/category'
import { uploadFile } from '@/api/upload'

export default {
  name: 'EnterpriseAdd',
  data() {
    return {
      id: '',
      categoryList: [], // 类型列表
      formData: {
        value: "",
      },
      dialogVisible: false,
      value1: '',
      ruleForm: {
        name: '',
        industry: '',
        high_tech: '',
        datatype: '',
        parks: '',
        is_leading: '',
        is_service: '',
        is_research: '',
        introduction: '',
        img: [],
        honor: '',
        service_info: '',
        achievement: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入企业名称', trigger: 'blur' },
        ],
        industry: [
          { required: true, message: '请选择行业类型', trigger: 'change' }
        ],
        high_tech: [
          { required: true, message: '请选择高新技术类型', trigger: 'change' }
        ],
        datatype: [
          { required: true, message: '请选择数据总览类型', trigger: 'change' }
        ],
        parks: [
          { required: true, message: '请选择所在园区', trigger: 'change' }
        ],
        is_leading: [
          { required: true, message: '请选择是否龙头企业', trigger: 'change' }
        ],
        is_service: [
          { required: true, message: '请选择是否第三方机构', trigger: 'change' }
        ],
        is_research: [
          { required: true, message: '请选择是否研发机构', trigger: 'change' }
        ],
        introduction: [
          { required: true, message: '请输入企业简介', trigger: 'blur' }
        ],
        honor: [
          { required: true, message: '请输入企业荣誉', trigger: 'blur' }
        ],
        service_info: [
          { required: true, message: '请输入服务案例', trigger: 'blur' }
        ],
        achievement: [
          { required: true, message: '请输入研究成果', trigger: 'blur' }
        ],
      }
    };
  },
  created() {
    this.getCategory()
    let id = this.$route.params.id
    if (id) {
      this.getInfo(id)
      this.id = id
    }

  },
  components: { Tinymce },
  methods: {
    getInfo(id) {
      companyInfo({ id }).then(res => {
        const { code, data, msg } = res
        if (code === 200) {
          const { name, industry, high_tech, datatype, parks, is_leading, is_service, is_research, introduction, img, honor, service_info, achievement, sort } = data
          this.ruleForm = {
            name,
            industry: industry.id,
            high_tech: high_tech.id,
            datatype: datatype.id,
            parks: parks.id,
            is_leading,
            is_service,
            is_research,
            introduction,
            img,
            honor,
            service_info,
            achievement,
            sort
          }
        } else {
          this.$message.error(msg)
        }
      })
    },
    // 添加/修改企业
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const http = this.id ? editCompany : addCompany
          const { name, industry, high_tech, datatype, parks, is_leading, is_service, is_research, introduction, img, honor, service_info, achievement, sort } = this.ruleForm
          const data = this.id ? { name, industry, high_tech, datatype, parks, is_leading, is_service, is_research, introduction, img, honor, service_info, achievement, sort, id: this.id } : this.ruleForm
          http(data).then(res => {
            if (res.code === 200) {
              this.$message.success(this.id ? '添加成功！' : '修改成功')
              this.$router.push('/company/company')
            } else {
              this.$message.success(this.id ? '添加失败！' : '修改失败' || res.msg)
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 轮播图上传
    bannerPictureUpload(params) {
      this.thumbLoad = true
      const file = params.file
      const imgType = ['image/png', 'image/jpg', 'image/jpeg']
      if (imgType.indexOf(file.type) === -1) {
        this.$message.warning('上传图片格式必须为: png或jpg格式')
        return false
      }
      const formData = new FormData()
      formData.append('file', file)
      formData.append('dir', 'image/company')
      uploadFile(formData)
        .then(res => {
          this.thumbLoad = false
          try {
            const { message, code, data } = res
            if (code === 200) {
              // 域名/storage/ 拼接
              this.ruleForm.img.push('http://api.xysyszhd.dev.xmnk.cn/storage/' + data)
            } else {
              this.$message.error(message)
            }
          } catch (e) {
            console.log(`上传轮播图失败: ${e}`)
          }
        })
        .catch(() => {
          this.thumbLoad = false
        })
    },
    // 删除某一个轮播图
    deleteBanner(i) {
      this.ruleForm.img.splice(i, 1)
    },
    // 获取列表
    async getCategory() {
      try {
        const res = await companyCategory()
        const { msg, code, data } = res
        if (code === 200) {
          this.categoryList = data
        } else {
          this.$message.error(msg)
        }
      } catch (e) {
        console.log(`获取列表失败:${e}`)
      }
    },
    // 修改类型
    editItem(fid, isEdit, info, idx) {
      this.addItem(fid, isEdit, info, idx)
    },
    // 添加/修改类型
    addItem(fid, isEdit, info, idx) {
      if (info && info != null && isEdit !== 1) {
        this.$message.error('无可编辑内容')
        return
      }
      let val = ''
      if (info) {
        const index = this.categoryList[idx].children.findIndex((e) => e.id === info.id)
        const obj = this.categoryList[idx].children[index]
        val = obj.name
      }
      this.$prompt(' 请输入新的类型名称 ', isEdit === 1 ? '编辑' : '添加', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: val
      }).then(async ({ value }) => {
        if (!value || value === '') {
          this.$message.error('类型名称不能为空!')
        } else {
          const http = isEdit === 1 ? editCategory : addCategory
          const data = isEdit === 1 ? { fid, id: info.id, name: value } : { fid, name: value }
          http(data).then(res => {
            if (res.code === 200) {
              this.$message.success(isEdit === 1 ? '修改类型成功' : '添加类型成功')
              this.getCategory()
            } else {
              this.$message.success(res.msg || isEdit === 1 ? '修改类型失败' : '添加类型失败')
            }
          })
        }
      })
    },
    // 删除类型
    deleteItem(info) {
      this.$confirm("确定要删除" + "' " + info.name + " '" + "吗？", "删除", {
        type: 'warning'
      })
        .then(() => {
          // 本地静态删除
          deleteCategory({ id: info.id }).then(res => {
            if (res.code === 200) {
              this.$message.success('删除成功')
              this.getCategory()
            } else {
              this.$message.error(res.message || '删除失败')
            }
          })
        })
        .catch(() => { });
    },
    // 下拉时显示底下的新增按钮
    visibleChange(visible, refName, fid) {
      if (visible) {
        const ref = this.$refs[refName][0];
        let product = ref.$refs.popper;
        if (product.$el) product = product.$el;
        if (
          !Array.from(product.children).some(
            (v) => v.className === "el-template-menu__list"
          )
        ) {
          const el = document.createElement("ul");
          el.className = "el-template-menu__list";
          el.style =
            "border-top:2px solid rgb(219 225 241); padding:0; color:rgb(64 158 255);font-size: 13px";
          el.innerHTML = `<li class="el-cascader-node text-center" style="height:37px;line-height: 50px;margin-left:10px;">
            <span class="el-cascader-node__label"><i class="font-blue el-icon-plus"></i> 新增</span>
            </li>`;
          product.appendChild(el);
          // 新增按钮点击事件
          el.onclick = () => {
            this.addItem(fid, 0);
          };
        }
      }
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>
<style lang="scss" scoped>
.info {
  padding: 24px;
  box-sizing: border-box;

  .el-input,
  .el-select {
    width: 300px;
  }
}
</style>