<template>
  <div>
    <el-dialog :visible.sync="addOrUpdateVisibleCopy" :title="modalTypeText[modalType]" @close="closeModal"
      :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="first-title">
        填写字段
      </div>
      <el-checkbox-group v-model="checkList" @change="changeBtn" style="margin-bottom: 20px">
        <el-checkbox-button v-for="(item) in btnList" :label="item" :key="item">{{ item }}
        </el-checkbox-button>
      </el-checkbox-group>

      <!-- 挂载和修改   -->
      <div key="1">
        <el-form :model="dataForm" :rules="rules" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()"
          :label-width="$i18n.locale === 'en-US' ? '120px' : '100px'">
          <!-- 基本信息 -->
          <div style="margin-bottom:40px" v-show="checkList.includes('基本信息')">
            <div style="
                text-align: center;
                font-weight: 600;
                font-size: 18px;
                margin-bottom: 10px;
              ">
              基本信息
            </div>
            <el-form-item label="名称" prop="name">
              <el-input v-model="dataForm.name" placeholder="请输入名称" style="width:90%"></el-input>
            </el-form-item>
            <el-form-item label="描述" prop="description">
              <el-input type="textarea" :rows="3" v-model="dataForm.description" placeholder="请输入描述" style="width:90%">
              </el-input>
            </el-form-item>

            <el-form-item label="图片">
              <el-upload ref="editUpload" class="upload-demo" :action="fileUploadUrl"
                :on-success="eidtHandleAvatarSuccess" :before-upload="editBeforeAvatarUpload" :limit="1" :file-list="[]"
                :on-remove="editUploadRemoveFile" :on-exceed="handleExceed" list-type="picture">
                <el-button size="small" type="primary" class="button-new">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传图片文件</div>
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              </el-upload>
            </el-form-item>

          </div>

          <!-- 场景痛点 -->
          <div class="" style="padding-bottom:40px" v-show="checkList.includes('场景痛点')">
            <scene-one-input :dataForm="dataForm" @update="updateDataForm" ref="scenePainDom" title="场景痛点"
              :keyTextObj="painKeyTextObj"></scene-one-input>
          </div>

          <!-- 解决方案 -->
          <div class="" style="padding-bottom:40px" v-show="checkList.includes('解决方案')">
            <scene-one-input :dataForm="dataForm" @update="updateDataForm" ref="solutionDom" title="解决方案"
              :keyTextObj="solutionKeyTextObj"></scene-one-input>
          </div>

          <!-- 组合能力 -->
          <div class="" style="padding-bottom:40px" v-show="checkList.includes('组合能力')">
            <div class="title">
              组合能力
            </div>
            <InfrastructureModal v-model="dataForm" :dataForm="dataForm" @update="updateDataForm" type="基础设施"
              :modalType="modalType" ref="jcssDom"></InfrastructureModal>
            <combine-ability v-model="dataForm" :dataForm="dataForm" @update="updateDataForm" type="数据资源" ref="sjzyDom"
              :getDataParams="getListParams['数据资源']"></combine-ability>
            <combine-ability v-model="dataForm" :dataForm="dataForm" @update="updateDataForm" type="组件服务" ref="zjfwDom"
              :getDataParams="getListParams['组件服务']"></combine-ability>
          </div>

          <!-- 更多能力 -->
          <div class="" style="marigin-bottom:40px" v-show="checkList.includes('更多能力')">
            <common-question :dataForm="dataForm" @update="updateDataForm" ref="moreAbilityDom" title="更多能力"
              :keyTextObj="moreKeyTextObj">
            </common-question>
          </div>

          <!-- 使用步骤 -->
          <div style="marigin-bottom:20px" v-show="checkList.includes('使用步骤')">
            <scene-use-step :dataForm="dataForm" @update="updateDataForm" ref="sceneUseUpDom">
            </scene-use-step>
          </div>
        </el-form>
      </div>
      <template slot="footer">
        <el-button @click="closeModal">{{ $t("cancel") }}</el-button>
        <el-button type="primary" @click="dataFormSubmitHandle()">{{
            $t("confirm")
        }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import debounce from "lodash/debounce";
import qs from "qs";
import SceneUseStep from './components/scene-use-step.vue';
import SceneOneInput from './components/scene-one-input.vue';
import CombineAbility from '../components/combine-ability.vue';
import CommonQuestion from '../components/common-question.vue';
import InfrastructureModal from './components/infrastructure-modal.vue'
import Cookies from 'js-cookie'
import upload from '@/views/modules/components/upload'

let btnArray = ['基本信息', '场景痛点', '解决方案', '组合能力', '更多能力', '使用步骤']
// 数据资源\组件服务
export const getJson = (type) => {
  return {
    methods: 'get',
    url: '/census/center/selectResourceListByType',
    postData: {
      type
    }
  }
}
export const getDescJson = (text) => {
  return {
    descObj: {
      text: `${text}描述`,
      key: 'description'
    },
  }
}
// 弹框的方法
export const getListParams = {
  '数据资源': getJson('数据资源'),
  '组件服务': getJson('组件服务'),
  '基础设施': ''
}
// 模态框标题
export const modalTypeText = {
  add: '挂接',
  update: '修改'
}

export const getFuseResourceList = (abilityListObj) => {
  let arr = []
  let length = 0
  for (const key in abilityListObj) {
    if (Object.hasOwnProperty.call(abilityListObj, key)) {
      const itemArray = abilityListObj[key];
      itemArray.map((v, i) => {
        let index = (i + 1) + length
        arr.push({
          resourceId: v,
          type: key,
          sequence: index
        })
      })
      length = itemArray.length
    }
  }
  return arr
}

export default {
  components: {
    SceneUseStep,
    CombineAbility,
    SceneOneInput,
    upload,
    CommonQuestion,
    InfrastructureModal,
  },
  data() {
    return {
      fileUploadUrl: window.SITE_CONFIG.apiURL + '/upload',
      moreKeyTextObj: {
        nameObj: {
          text: '能力名称',
          key: 'name'
        },
        ...getDescJson('能力'),
      },
      painKeyTextObj: getDescJson('痛点'),
      solutionKeyTextObj: getDescJson('方案'),
      dataForm: {
        "name": "",
        "applicationArea": "",
        "description": "",
        "fuseAttrList": [
          {
            "attrType": "使用步骤",
            "attrValue": [{ question: "", answer: "" }],
          },
          {
            "attrType": "更多能力",
            "attrValue": [{ name: "", description: "" }],
          },
          {
            "attrType": "场景痛点",
            "attrValue": [{ description: "" }],
          },
          {
            "attrType": "解决方案",
            "attrValue": [{ description: "" }],
          },
          {
            "attrType": "服务图片",
            "attrValue": "",
          },
        ],
        "fuseResourceList": [],
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入名称",
            trigger: "change",
          },
        ],
        description: [
          {
            required: true,
            message: "请输入描述",
            trigger: "change",
          },
        ],
      },
      checkList: JSON.parse(JSON.stringify(btnArray)),
      btnList: JSON.parse(JSON.stringify(btnArray)),
      addOrUpdateVisibleCopy: this.addOrUpdateVisible,
      displayInfo: {
        'name': '名称',
        'description': '描述',
      },
      modalTypeText: modalTypeText,
      refsParseArray: {
        'sceneUseUpDom': '使用步骤',
        'moreAbilityDom': '更多能力',
        'scenePainDom': '场景痛点',
        'solutionDom': '解决方案',
        'zjfwDom': '组件服务',
        'sjzyDom': '数据资源',
        'jcssDom': '基础设施',
      },
      getListParams: getListParams,
      abilityListObj: {},
      imgData: [],
      // 限定图片
      handleExceed() {
        this.$message({ type: 'error', message: '最多支持一张图片上传' })
      },
      imageUrl: '',
    };
  },
  props: {
    modalType: {
      type: String,
      default: 'add'
    },
    addOrUpdateVisible: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    dataForm: {
      handler(newVal) {
        this.dataForm = newVal
      },
      deep: true,
      immediate: true,
    },
    addOrUpdateVisible: {
      handler(newVal) {
        this.addOrUpdateVisibleCopy = newVal;
        if (this.modalType == 'add' && newVal) {
          localStorage.setItem('InfrastructureSearchData', JSON.stringify({}))
          this.getDetail(this.dataForm)
        }
      },
      immediate: true,
    }
  },
  methods: {
    clearForm() {
      this.$refs.dataForm && this.$refs.dataForm.resetFields();
    },
    closeModal() {
      this.$emit('closeModal')
    },
    // 更新表单
    updateDataForm(data) {
      if (Object.keys(this.getListParams).includes(data.title)) {
        this.abilityListObj[data.title] = data.list;
      } else {
        // 更多能力、使用步骤
        this.operateFuseAttrList(data.title, data)
      }
    },
    getFuseResourceList() {
      return getFuseResourceList(this.abilityListObj)
    },
    operateFuseAttrList(title, data) {
      if (this.dataForm.fuseAttrList.every(v => v.attrType !== title)) {
        this.dataForm.fuseAttrList.push({
          'attrType': title,
          'attrValue': JSON.stringify(data.list)
        })
      } else {
        this.dataForm.fuseAttrList.map(v => {
          if (v.attrType === title) {
            v.attrValue = JSON.stringify(data.list)
          }
        })
      }
    },
    // 改变按钮状态
    changeBtn(data) {
      this.checkList = data;
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs.dataForm.validate((valid) => {
          if (!valid) {
            this.$message.error("请检查表单是否填写完整");
            return false;
          }
          let methodsObj = {
            'add': 'post',
            'update': 'put'
          }
          this.dataForm.fuseResourceList = this.getFuseResourceList()
          if (this.imageUrl == '') {
            this.$message.error("请上传图片！");
            return;
          }
          this.dataForm.fuseAttrList.find(v => v.attrType == '服务图片').attrValue = this.imageUrl || '';
          let _obj = Object.assign({}, this.dataForm, {
            type: '赋能场景'
          })
          console.log('this.dataForm------表单提交------>', this.dataForm);
          this.$http
          [methodsObj[this.modalType]]("/fuse", _obj)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.$refs.dataForm && this.$refs.dataForm.resetFields();
                  this.$emit("refreshDataList");
                  this.$emit("closeModal");
                },
              });
            })
            .catch((err) => {
              this.$message.error(err)
            });
        });
      },
      1000,
      { leading: true, trailing: false }
    ),
    // 详情
    getDetail(data) {
      console.log('data---详情--------->', data);
      this.dataForm = data;
      this.$nextTick(() => {
        for (const key in this.refsParseArray) {
          this.$refs[key] && this.$refs[key].getDataInfo && this.$refs[key].getDataInfo(data)
        }
        let _imgObj = data.fuseAttrList.find(v => v.attrType == '服务图片') || {};
        this.imageUrl = _imgObj.attrValue;

        // 组合能力--特殊处理
        Object.keys(this.getListParams).map(k => {
          let arr = data.fuseResourceList.filter(v => v.type == k);
          let arr2 = [];
          arr.map(v => {
            arr2.push(v.resourceId)
          })
          this.abilityListObj[k] = arr2
        })
      })
    },
    handleAvatarSuccess(res, file) {
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.imageUrl = res.data
    },
    beforeAvatarUpload(file) {
      const isImage =
        file.type === 'image/jpeg' ||
        file.type === 'image/jpg' ||
        file.type === 'image/png'
      if (!isImage) {
        this.$message.error('上传头像图片只能是 jpg/png 格式!')
      }
      return isImage
    },
    addUploadRemoveFile(file, fileList) {
      this.$refs.addUpload.clearFiles()
      this.imageUrl = ''
    },
    editBeforeAvatarUpload(file) {
      const isImage =
        file.type === 'image/jpeg' ||
        file.type === 'image/jpg' ||
        file.type === 'image/png'

      if (!isImage) {
        this.$message.error('上传头像图片只能是 jpg/png 格式!')
      }
      return isImage
    },
    editUploadRemoveFile(file, fileList) {
      this.$refs.editUpload.clearFiles()
      this.imageUrl = ''
    },
    eidtHandleAvatarSuccess(res, file) {
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.imageUrl = res.data
    },
  },
  beforeDestroy() {
    this.clearForm()
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  height: 580px;
  overflow: auto;
}

.icon-input ::v-deep .el-input__inner {
  cursor: pointer;
}

.detial-form ::v-deep {
  .el-form-item {
    margin-bottom: 0px;
    line-height: 32px;
  }

  .el-form-item__label {
    line-height: 32px;
  }

  .el-form-item__content {
    line-height: 32px;
  }
}

::v-deep .el-checkbox-button__inner {
  width: 130px;
  margin: 0 10px 5px;
  border-left: unset !important;
  border-radius: unset !important;
  border: 1px solid #dcdfe6 !important;
}
</style>

<style lang="scss" scoped>
.mod-sys__menu {

  .menu-list,
  .icon-list {

    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }

  &-icon-popover {
    width: 458px;
    overflow: hidden;
  }

  &-icon-inner {
    width: 478px;
    max-height: 258px;
    overflow-x: hidden;
    overflow-y: auto;
  }

  &-icon-list {
    width: 458px;
    padding: 0;
    margin: -8px 0 0 -8px;

    >.el-button {
      padding: 8px;
      margin: 8px 0 0 8px;

      >span {
        display: inline-block;
        vertical-align: middle;
        width: 18px;
        height: 18px;
        font-size: 18px;
      }
    }
  }
}

.previewImg {
  position: fixed;
  z-index: 9999;
}

.name {
  text-align: right;
  vertical-align: middle;
  font-size: 14px;
  color: #606266;
  line-height: 40px;
  padding: 0 12px 0 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  line-height: 32px;
  width: 120px;
}

.text {
  margin-left: 132px;
  font-size: 14px;
  color: #606266;
  line-height: 32px;
}

.title {
  text-align: center;
  font-weight: 600;
  font-size: 18px;
  margin-bottom: 10px;
}

.first-title {
  text-align: center;
  font-weight: 600;
  font-size: 18px;
  margin-bottom: 10px;
}

.avatar {
  height: 100px;
  width: 100px;
  display: block;
}
</style>
