<template>
  <el-card shadow="never" class="aui-card--fill">
    <div class="mod-ability__bsabilityai">
      <el-form :inline="true" :model="dataForm">
        <el-form-item>
          <el-input
            v-model="dataForm.name"
            placeholder="名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="getDataList2(dataForm.name)">{{
            $t("query")
          }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="info" @click="exportHandle()">{{
            $t("export")
          }}</el-button>
        </el-form-item>
        <!-- <el-form-item>
          <el-button
            v-if="$hasPermission('ability:bsabilityai:save')"
            type="primary"
            @click="addOrUpdateHandleServe()"
            >挂接</el-button
          >
        </el-form-item> -->
        <el-form-item>
          <el-button
            type="primary"
            @click="showPutOnTheShelf()"
            >盘点入库</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            v-if="$hasPermission('ability:bsabilityai:delete')"
            type="danger"
            @click="deleteHandle2()"
            >{{ $t("deleteBatch") }}</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="dataListLoading"
        :data="dataList"
        border
        @selection-change="dataListSelectionChangeHandle"
        height="650px"
      >
        <el-table-column
          type="selection"
          header-align="center"
          align="center"
          width="50"
        ></el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          prop="name"
          label="系统名称"
          header-align="center"
          align="center"
        ></el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          prop="description"
          label="能力描述"
          header-align="center"
          align="center"
        ></el-table-column>
         <el-table-column
          :show-overflow-tooltip="true"
          prop="belongProject"
          label="归属项目"
          header-align="center"
          align="center"
        ></el-table-column>
         <el-table-column
          :show-overflow-tooltip="true"
          prop="belongSystem"
          label="归属系统"
          header-align="center"
          align="center"
        ></el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          prop="deptName"
          label="归属部门"
          header-align="center"
          align="center"
        ></el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          prop="deptContacts"
          label="注册者"
          header-align="center"
          align="center"
        ></el-table-column>
        <!-- <el-table-column
          :show-overflow-tooltip="true"
          width="280"
          prop="shareCondition"
          label="共享条件"
          header-align="center"
          align="center"
        ></el-table-column> 
        <template v-if="dataList[0] && dataList[0].infoList2">
          <el-table-column
            v-for="(item, index) in dataList[0].infoList2"
            :key="Math.random()"
            :label="item.attrType"
            header-align="center"
            align="center"
            :show-overflow-tooltip="true"
            width="280"
          >
            <template slot-scope="scope">
              {{ findValue(scope.row.infoList2, item.attrType) }}
            </template>
          </el-table-column>
        </template>-->
        <el-table-column
          label="操作"
          fixed="right"
          header-align="center"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="UpdateData(scope.row)"
              >{{ $t("update") }}</el-button
            >
            <el-button type="text" size="small" @click="showDetail(scope.row)"
              >详情</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="applyAndAssembly(scope.row)"
              >标签化</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="limit"
        :total="Number(total)"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="pageSizeChangeHandle"
        @current-change="pageCurrentChangeHandle"
      >
      </el-pagination>
      <!-- 弹窗, 新增 / 修改 -->
      <add-or-update
        :disabled="disabled"
        v-if="addOrUpdateVisible"
        ref="addOrUpdate"
        @refreshDataList="getDataList"
      ></add-or-update>
      <relate-application
        v-if="relateApplicationResourceVisible"
        ref="relateApplication"
        :relateInfo="relationData"
        :nameArray="topNameArray"
        @isShowRelatePopup="handleIsShowRelatePopupApply"
      ></relate-application>
    </div>
     <el-dialog
      title="盘点入库"
      :visible.sync="showPutOnTheShelfFlag2"
      :close-on-click-modal='false'
      :close-on-press-escape='false'
      :destroy-on-close='true'
      :before-close='clear'
      width="50%">
      <putOnTheShelf :required="required" :notFilled="notFilled":putOnTheShelfList='putOnTheShelfList' @changeInfoList='changeInfoList' :type='radio' :typeInput='typeInput'></putOnTheShelf>
      <span slot="footer" class="dialog-footer">
        <el-button @click="clear">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import AddOrUpdate from './bsabilityservice-add-or-update'
import dictionaries from '@/utils/dictionaries'
import RelateApplication from './bsabilityai-relate-application.vue'
import qs from 'qs'
import { type } from 'os'
import putOnTheShelf from '@/views/modules/putOnTheShelf'

export default {
  mixins: [mixinViewModule],
  data () {
    return {
      required: ['归属部门', '部门联系人', '部门联系人电话', '应用领域', '共享条件', '应用名称', '应用描述', '应用类型'],
      notFilled: [],
      mixinViewModuleOptions: {
        getDataListURL: '/resource/page',
        getDataListIsPage: true,
        exportURL: '/ability/bsabilityai/export',
        deleteURL: '/resource/delete',
        deleteIsBatch: true
      },
      disabled: false,
      sceneArr: dictionaries.sceneArr,
      fieldArr: dictionaries.fieldArr,
      shareFormArr: dictionaries.shareFormArr,
      dataForm: {
        name: '',
        creator: '',
        selectType: 0,
        delFlag: 0,
        type: '应用系统'
      },
      qp: false,
      relateApplicationResourceVisible: false,
      relationData: {}, // 打开穿梭框时传递的参数
      topNameArray: [], //
      radio: '应用系统',
      insertList: [],
      putOnTheShelfList: [],
      showPutOnTheShelfFlag2: false,
      submitFrom: {
        type: '应用系统',
        deptId: '',
        delFlag: 0,
        infoList: [
          // {
          //   attrType: '组件类型',
          //   attrValue: '',
          //   delFlag: 0
          // }
        ]
      },
      typeInput: '应用系统'
    }
  },
  watch: {},
  components: {
    AddOrUpdate,
    RelateApplication,
    putOnTheShelf
  },
  created () {
    this.dataForm.name = ''
    this.dataForm.type = '应用系统'
  },
  mounted () {
    // window.addEventListener('resize', this.a)
    // this.fullScreen()
  },
  methods: {
    reset () {
      this.$http
        .get(
          this.mixinViewModuleOptions.getDataListURL +
            '?' +
            qs.stringify({
              // order: this.order,
              // orderField: this.orderField,
              // type: '组件服务',
              page: 1,
              selectType: 0,
              limit: 10,
              delFlag: 0,
              creator: '',
              type: '应用系统',
              name: ''
            })
        )
        .then(({ data: res }) => {
          this.dataForm.name = ''
          if (res.code !== 0) {
            this.dataList = []
            this.total = 0
            return this.$message.error(res.msg)
          }
          this.dataList = this.mixinViewModuleOptions.getDataListIsPage
            ? res.data.list
            : res.data 
          this.total = this.mixinViewModuleOptions.getDataListIsPage
            ? res.data.total
            : 0;
          if(this.dataList.length>0){
            this.dataList.forEach((item)=>{
              item.belongProject = "城市信息模型";
              item.belongSystem = "信息模型技术平台";
            });
          }
          if (this.mixinViewModuleOptions.requestCallback) {
            this.mixinViewModuleOptions.requestCallback(res.data)
          }
          this.dataListLoading = false
          this.dataList.map((item, index) => {
            const dataListSinforList = []
            item.infoList.map((itemson, indexson) => {
              if (
                itemson.attrType === '应用领域'
              ) {
                dataListSinforList.push(itemson)
              }
            })
            this.dataList[index].infoList2 = dataListSinforList
          })
        })
        .catch(() => {
          this.dataListLoading = false
        })
    },
    showDetail (val) {
      window.open(window.SITE_CONFIG.previewUrl + '#/details?id=' + val.id)
      // this.addOrUpdateVisible = true
      // this.disabled = false
      // this.$nextTick(() => {
      //   this.$refs.addOrUpdate.UpdateState = false
      //   this.$refs.addOrUpdate.dataFormShowDetails = val
      //   this.$refs.addOrUpdate.init()
      // })
      // this.disabled = true
    },
    showDocument (val) {
      console.log(val)
      window.open(
        window.SITE_CONFIG.frontUrl + '?id=' + val.id + '&&type=' + val.type,
        '_blank'
      )
    },
    findValue (list, type) {
      const found = list.find((item) => item.attrType === type)
      if (found) {
        return found.attrValue
      } else {
        return '暂无数据'
      }
    },
    getDataList2 (names) {
      if (names != null) {
        this.$http
          .get(
            this.mixinViewModuleOptions.getDataListURL +
              '?' +
              qs.stringify({
                // order: this.order,
                // orderField: this.orderField,
                // type: '组件服务',
                pageNum: 1,
                pageSize: this.limit,
                type: '应用系统',
                creator: '',
                selectType: 0,
                delFlag: 0,
                name: names
              })
          )
          .then(({ data: res }) => {
            if (res.code !== 0) {
              this.dataList = []
              this.total = 0
              return this.$message.error(res.msg)
            }
            if (res.data.list.length >= 0) {
              this.dataList = res.data.list
              this.total = this.mixinViewModuleOptions.getDataListIsPage
                ? res.data.total
                : 0
              if (this.mixinViewModuleOptions.requestCallback) {
                this.mixinViewModuleOptions.requestCallback(res.data)
              }
              this.dataListLoading = false
              this.dataList.map((item, index) => {
                const dataListSinforList = []
                item.infoList.map((itemson, indexson) => {
                  if (
                    itemson.attrType === '应用领域'
                  ) {
                    dataListSinforList.push(itemson)
                  }
                })
                this.dataList[index].infoList2 = dataListSinforList
              })
            } else {
              this.$message.error('未查询到相关信息')
              this.reset()
            }
          })
          .catch(() => {
            this.dataListLoading = false
          })
      } else {
        this.$message.error('查询不能输入为空')
      }
    },
    // fullScreen () {
    //   if (window.outerHeight === screen.availHeight) {
    //     if (window.outerWidth === screen.availWidth) {
    //       console.log(
    //         '全屏1',
    //         window.outerHeight,
    //         screen.availHeight,
    //         window.outerWidth,
    //         screen.availWidth
    //       )
    //       this.qp = false
    //     } else {
    //       console.log(
    //         '不是全屏2',
    //         window.outerHeight,
    //         screen.availHeight,
    //         window.outerWidth,
    //         screen.availWidth
    //       )
    //       this.qp = true
    //     }
    //   } else {
    //     console.log(
    //       '不是全屏3',
    //       window.outerHeight,
    //       screen.availHeight,
    //       window.outerWidth,
    //       screen.availWidth
    //     )
    //     this.qp = true
    //   }
    // },
    // 应用与组件
    applyAndAssembly (val) {
      console.log('vvvv', val)
      // 根据id和类型查询已关联的组件，将id,type和查出来的数据传递给组件
      const type = '组件服务'
      const id = val.id
      this.$http
        .get('/dataResourceRel/queryResourceRelByKeyId', {
          params: {
            keyId: id,
            type: type,
            referenceName: ''
          }
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          console.log('rrrrressssz', res.data)
          this.relateApplicationResourceVisible = true
          this.relationData = {
            id: id,
            linkType: '1',
            responseData: res.data
          }
          this.topNameArray = ['未关联标签名称', '已关联标签名称']
          console.log(' this.relationData', this.relationData)
          // 将数据传递给引入的组件
        })
    },
    // 应用与数据资源
    applyAndDataResource (val) {
      console.log('数据资源')
    },
    // 应用与项目
    applyAndProject (val) {
      const type = '项目'
      const id = val.id
      this.$http
        .get('/dataResourceRel/queryResourceRelByKeyId', {
          params: {
            keyId: id,
            type: type,
            referenceName: ''
          }
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          console.log('rrrrressssx', res.data)
          this.relateApplicationResourceVisible = true
          this.relationData = {
            id: id,
            linkType: '1',
            responseData: res.data
          }
          this.topNameArray = ['未关联项目名称', '已关联项目名称']
          // 将数据传递给引入的组件
        })
    },
    // 应用与基础设施
    applyAndInfrastructure (val) {
      const type = '基础设施'
      const id = val.id
      this.$http
        .get('/dataResourceRel/queryResourceRelByKeyId', {
          params: {
            keyId: id,
            type: type,
            referenceName: ''
          }
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          console.log('rrrrressssj', res.data)
          this.relateApplicationResourceVisible = true
          this.relationData = {
            id: id,
            linkType: '1',
            responseData: res.data
          }
          this.topNameArray = ['未关联基础设施名称', '已关联基础设施名称']
          // 将数据传递给引入的组件
        })
    },
    // 是否展示关联应用弹窗
    handleIsShowRelatePopupApply (type) {
      this.relateApplicationResourceVisible = type
    },
    // 新上架
    clear () {
      this.notFilled = []
      this.showPutOnTheShelfFlag2 = false
      this.insertList = []
      this.putOnTheShelfList = []
      this.radio = '应用系统'
      this.submitFrom = {
        type: '应用系统',
        deptId: '',
        delFlag: 0,
        infoList: [
          // {
          //   attrType: '组件类型',
          //   attrValue: '',
          //   delFlag: 0
          // }
        ]
      }
      this.reset()
    },
    // 上架
    showPutOnTheShelf () {
      //    :title="submitFrom.id?'修改'+radio:'上架'+radio"
      this.showPutOnTheShelfFlag2 = true
      this.$http.get('/category/getCategoryTree').then(res => {
        this.insertList = res.data.data.filter(item => item.name === '应用资源一')[0]
        console.log(this.insertList, this, this.radio, 'hhhhhhhhhhh')
        this.putOnTheShelfList = this.insertList.children
      })
    },
    changeInfoList (obj) {
      this.submitFrom.infoList = this.submitFrom.infoList.filter((item) => item.attrType !== obj.attrType)
      this.submitFrom.infoList.push(obj)
    },
    submitData () {
      const arr = []
      this.putOnTheShelfList.map(item => {
        item.children.map(child => {
          if (child.children) {
            if (child.name === '算法优势' || child.name === '应用场景' || child.name === '功能介绍') {
              arr.push(child.name)
              if (this.submitFrom.infoList.filter(value => value.attrType === child.name).length === 0) {
                this.submitFrom.infoList.push({
                  attrType: child.name,
                  attrValue: child.note1,
                  delFlag: 0
                })
              }
            }
            child.children.map(val => {
              arr.push(val.name)
              if (val.type === 'input' || val.type === 'textArea' || val.type === 'select' || val.type === 'checkBox' || val.type === 'radio') {
                this.submitFrom.infoList = this.submitFrom.infoList.filter((item) => item.attrType !== val.name)
              }
              if (val.note1 || val.note1) {
                switch (val.name) {
                  case '算法名称':
                  case '应用名称':
                  case '组件名称':
                  case '图层名称':
                    this.submitFrom.name = val.note1
                    break
                  case '算法描述':
                  case '应用描述':
                  case '组件描述':
                  case '图层描述':
                    this.submitFrom.description = val.note1
                    break
                  case '共享条件':
                    this.submitFrom.shareCondition = val.note1
                    break
                  case '共享类型':
                    this.submitFrom.shareType = val.note1
                    break
                  case '服务接口':
                    this.submitFrom.apiUrl = val.note1
                    break
                  case '接口请求方式':
                    this.submitFrom.apiMethodType = val.note1
                    break
                  case '访问地址':
                    this.submitFrom.link = val.note1
                    break
                  case '部门联系人':
                    this.submitFrom.deptContacts = val.note1
                    break
                  case '部门联系人电话':
                    this.submitFrom.deptPhone = val.note1
                    break
                  case '归属部门':
                    this.submitFrom.deptId = val.note1
                    break
                  case '能力类型':
                    this.submitFrom.type = val.note1
                    break
                  default:
                    if (val.type !== 'image' && val.type !== 'file' && val.type !== 'video') {
                      this.submitFrom.infoList.push({
                        attrType: val.name,
                        attrValue: val.note1,
                        delFlag: 0
                      })
                    } else {
                      if (this.submitFrom.infoList.filter(value => value.attrType === val.name).length === 0) {
                        this.submitFrom.infoList.push({
                          attrType: val.name,
                          attrValue: val.note1,
                          delFlag: 0,
                          note2: val.note2 || null
                        })
                      }
                    }
                    break
                }
              }
            })
          }
        })
      })
      this.submitFrom.infoList = this.submitFrom.infoList.sort((a, b) => arr.indexOf(a.attrType) - arr.indexOf(b.attrType))
      this.notFilled = []
      console.log(this.submitFrom, '表单验证')
      if (!this.submitFrom.name) {
        this.notFilled.push('应用名称')
      }
      if (!this.submitFrom.description) {
        this.notFilled.push('应用描述')
      }
      if (!this.submitFrom.shareCondition) {
        this.notFilled.push('共享条件')
      }
      if (!this.submitFrom.deptId) {
        this.notFilled.push('归属部门')
      }
      if (!this.submitFrom.deptContacts) {
        this.notFilled.push('部门联系人')
      }
      if (!this.submitFrom.deptPhone) {
        this.notFilled.push('部门联系人电话')
      }
      if (!this.submitFrom.infoList.filter(val => val.attrType == '应用领域')[0] || !this.submitFrom.infoList.filter(val => val.attrType == '应用领域')[0].attrValue) {
        this.notFilled.push('应用领域')
      }
      // if (!this.submitFrom.infoList.filter(val => val.attrType == '应用状态')[0] || !this.submitFrom.infoList.filter(val => val.attrType == '应用状态')[0].attrValue) {
      //   this.notFilled.push('应用状态')
      // }
      if (!this.submitFrom.infoList.filter(val => val.attrType == '应用类型')[0] || !this.submitFrom.infoList.filter(val => val.attrType == '应用类型')[0].attrValue) {
        this.notFilled.push('应用类型')
      }
      if (this.notFilled.length > 0) {
        this.$message({
          message: '请填写必填字段！',
          type: 'warning'
        })
      } else {
        if (this.submitFrom.id) {
        // 解决编辑无组件类型
          this.submitFrom.infoList.map(val => {
            if (val.attrType === '组件类型') {
              val.attrValue = this.radio
            }
          })
          console.log('编辑===============>', this.submitFrom)
          // 检验是否有空值
          this.submitFrom.infoList = this.submitFrom.infoList.filter(item => item.attrValue)
          this.$http
            .put('/resource/update', this.submitFrom)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                this.$message.error('修改失败!')
                this.showPutOnTheShelfFlag2 = false
              } else {
                this.$message.success('修改成功！')
                this.showPutOnTheShelfFlag2 = false
                this.clear()
              }
            })
            .catch(() => {})
        } else {
          this.$http
            .post('/resource/insert?source= b', this.submitFrom)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                this.$message.error('上架失败!')
                this.showPutOnTheShelfFlag2 = false
              } else {
                this.$message.success('上架成功！')
                this.showPutOnTheShelfFlag2 = false
                this.clear()
              }
            })
            .catch(() => {})
        }
      }
    },
    // 新修改
    UpdateData (item) {
      this.$http.get('/category/getCategoryTree').then(res => {
        this.insertList = res.data.data.filter(item => item.name === '应用资源一')[0]
        this.radio = '应用系统'
        // this.radio = item.infoList.filter(val => val.attrType === '应用系统')[0].attrValue
        this.putOnTheShelfList = this.insertList.children
        // this.putOnTheShelfList = this.insertList.children.filter(item => item.name === this.radio)[0].children
        this.putOnTheShelfList.map(parent => {
          parent.children.map(child => {
            if (child.name === '算法优势' || child.name === '应用场景' || child.name === '功能介绍') {
              const obj = item.infoList.filter(val => val.attrType === child.name)[0]
              if (obj) {
                child.note1 = obj.attrValue
              }
            } else {
              if (child.children) {
                child.children.map(data => {
                  if (data.name === '计费标准信息' || data.name === '常见问题') {
                    const obj = item.infoList.filter(val => val.attrType === child.name)[0]
                    if (obj) {
                      data.note1 = obj.attrValue
                    }
                  } else {
                    switch (data.name) {
                      case '算法名称':
                      case '应用名称':
                      case '组件名称':
                      case '图层名称':
                        data.note1 = item.name
                        break
                      case '算法描述':
                      case '应用描述':
                      case '组件描述':
                      case '图层描述':
                        data.note1 = item.description
                        break
                      case '共享条件':
                        data.note1 = item.shareCondition
                        break
                      case '共享类型':
                        data.note1 = item.shareType
                        break
                      case '服务接口':
                        data.note1 = item.apiUrl
                        break
                      case '接口请求方式':
                        data.note1 = item.apiMethodType
                        break
                      case '访问地址':
                        data.note1 = item.link
                        break
                      case '部门联系人':
                        data.note1 = item.deptContacts
                        break
                      case '部门联系人电话':
                        data.note1 = item.deptPhone
                        break
                      case '归属部门':
                        data.note1 = item.deptId
                        break
                      case '能力类型':
                        data.note1 = item.type
                        break
                      default:
                        // eslint-disable-next-line no-case-declarations
                        const obj1 = item.infoList.filter(val => val.attrType === data.name)[0]
                        if (obj1) {
                          data.note1 = obj1.attrValue
                        }
                        break
                    }
                    if (data.type === 'image' || data.type === 'file' || data.type === 'video') {
                      const obj1 = item.infoList.filter(val => val.attrType === data.name)[0]
                      if (obj1) {
                        data.note2 = obj1.note2
                      }
                    }
                  }
                })
              }
            }
          })
        })
        this.submitFrom.id = item.id
        this.showPutOnTheShelfFlag2 = true
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.el-tooltip__popper {
  max-width: 50%;
}
::v-deep .el-upload-list__item-name {
  width: 400px;
}
</style>
