<template>
  <div :class="$style.wrapHeight">
    <!-- 左侧 -->
    <audit-model-tree ref="tree" @treeSelect="treeSelect" @depChanged="depChanged">
      <div :class="$style.treeWrap">
        <!-- 我的模型 和分类管理并列 -->
        <div :class="$style.treeTitle">我的模型</div>
        <div :class="$style.treeContent">
          <a-button type="primary" @click="toModel('class')">分类管理</a-button>
        </div>
      </div>
    </audit-model-tree>
    <!-- 右侧 -->
    <a-card :class="$style.tableRight">
      <!-- 列表 -->
      <SdDataTable
        ref="table"
        :key="key"
        :columns="columns"
        :filter-expressions="expressions"
        :search-fields="['modelName']"
        :data-url="'api/xcoa-mobile/v1/iammodelmaintain/iamModelQueryList'"
        :actions="actions"
      >
        <!-- 共享，发布 -->
        <template slot="gx" slot-scope="text, record">
          <span v-if="record.shareStatus === null">未共享</span>
          <span v-else-if="record.shareStatus === 5">已共享</span>
          <span v-else>审核中</span>
        </template>
        <template slot="fb" slot-scope="text, record">
          <span v-if="record.publishStatus === null">未发布</span>
          <span v-else-if="record.publishStatus === 5 || record.publishStatus === 6">已发布</span>
          <span v-else>待审核</span>
        </template>
        <!-- 操作 -->
        <template slot="edit" slot-scope="text, record">
          <!-- 查看，共享，发布，删除，撤销共享 -->
          <!-- 未发布状态 显示发布 -->
          <!-- 已共享状态 显示撤销共享 -->
          <!-- 未共享状态 显示共享 -->
          <!-- 以共享 或发布则不能删除 -->
          <a :class="$style.edit" @click="toModel('read', record)">查看</a>
          <a
            v-if="record.publishStatus === null && record.reservelong2 === 1"
            :class="$style.edit"
            @click="toModel('fb', record)"
            >发布</a
          >
          <span v-else-if="record.publishStatus === null" :class="$style.edit" @click="openMessage"
            >发布</span
          >
          <a
            v-if="record.shareStatus === null && record.reservelong2 === 1"
            :class="$style.edit"
            @click="toModel('gx', record)"
            >共享</a
          >
          <span v-else-if="record.shareStatus === null" :class="$style.edit" @click="openMessage"
            >共享</span
          >
          <a v-if="record.shareStatus === 5" :class="$style.edit" @click="cancelShare(record)"
            >撤销共享</a
          >
          <a
            v-if="
              record.publishStatus !== 5 && record.publishStatus !== 6 && record.shareStatus !== 5
            "
            :class="$style.edit"
            @click="deleteModel(record)"
            >删除</a
          >
        </template>
      </SdDataTable>
    </a-card>
    <a-modal
      v-model="isShowSpace"
      centered
      title="自助建模"
      width="800px"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="close"
    >
      <a-form-model
        ref="spaceForm"
        :model="spaceForm"
        :rules="{
          modelName: [
            { required: true, message: '请输入模型名称', trigger: 'blur' },
            {
              validator: validatorModelName,
              trigger: 'blur',
            },
          ],
          modelType: [{ required: true, message: '请选择模型类型', trigger: 'blur' }],
          eventTag: [{ required: true, message: '请选择事件标签', trigger: 'blur' }],
          catalogName: [{ required: true, message: '请选择所属分类', trigger: 'blur' }],
          modelDomain: [{ required: true, message: '请选择模型领域', trigger: 'blur' }],

          creatModelType: [{ required: true, message: '请选择建模类型', trigger: 'blur' }],
        }"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <!-- 模型类型 必填-->

        <a-form-model-item label="模型类型" prop="modelType">
          <a-select
            v-model="spaceForm.modelType"
            allow-clear
            placeholder="请选择模型类型"
            @change="selectChangeModelType"
          >
            <a-select-option v-for="(item, i) in modelTypeOption" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <!-- 所属分类 只读输入框-->
        <a-form-model-item label="所属分类" prop="catalogName">
          <a-input v-model="spaceForm.catalogName" allow-clear :disabled="true" />
        </a-form-model-item>

        <!-- 模型名称 事件标签 都是必填 -->
        <a-form-model-item label="模型名称" prop="modelName">
          <a-input v-model="spaceForm.modelName" allow-clear />
        </a-form-model-item>
        <!-- 模型code -->
        <a-form-model-item label="模型领域" prop="modelDomain">
          <!-- <a-input v-model="spaceForm.modelCode" allow-clear /> -->
          <!-- modelDomain -->
          <a-select
            v-model="spaceForm.modelDomain"
            allow-clear
            placeholder="请选择模型领域"
            @change="modelDomainChange"
          >
            <a-select-option v-for="(item, i) in modelDomainOption" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <!-- 事件标签 -->
        <a-form-model-item label="事件标签分类" prop="eventTag">
          <a-select
            v-model="spaceForm.eventTag"
            allow-clear
            placeholder="请选择事件标签"
            @change="selectChangeEventTag"
          >
            <a-select-option v-for="(item, i) in eventTagList" :key="item.id" :value="item.id">
              {{ item.tagName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <!-- 建模类型 -->
        <a-form-model-item label="建模类型" prop="creatModelType">
          <a-select v-model="spaceForm.creatModelType" allow-clear placeholder="请选择建模类型">
            <a-select-option v-for="(item, i) in modelTypeList" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import components from './_import-components/audit-model-list-import'
import auditModelTree from './audit-model-tree.vue'
import TableActionTypes from '@/common/services/table-action-types'
import TableColumnTypes from '@/common/services/table-column-types'
import { generateTree, getTreeIds } from '@product/iam/audit/dataMarket/util'
import auditMaintainService from '../maintain/audit-maintain-service'
import { message, Modal } from 'ant-design-vue'
import auditModelService from './audit-model-service'
import SdDataTable from '@/common/components/sd-data-table.vue'
import { getUserInfo } from '@/common/store-mixin'
import axios from '@/common/services/axios-instance'
import debounce from 'lodash.debounce'

export default {
  name: 'AuditModelList',
  metaInfo: {
    title: '模型信息管理',
  },
  components: {
    ...components,
    auditModelTree,
    SdDataTable,
  },
  data() {
    return {
      key: 0,
      // 分类管理
      isShowSpace: false,
      confirmLoading: false,
      spaceForm: {
        modelName: null, // 模型名称
        // modelCode: null, // 模型code
        modelDomain: null, // 模型领域
        modelDomainName: null, // 模型领域名称
        modelType: null, // 模型类型
        modelTypeName: null, // 模型类型名称
        catalogId: null, // 分类id
        catalogName: null, // 分类名称
        eventTag: null, // 事件标签id
        eventTagName: null, // 事件标签名称
        source: 1, // 来源 1 自助建模 2 数据集建模
        creatorAccount: getUserInfo().account, // 当前登录人账户
        creatModelType: '',
      },
      // 模型领域
      modelDomainOption: [],
      // 模型类型 分析型 0 定位型-整改类 1 定位型-关注类 2
      modelTypeOption: [
        {
          id: 0,
          name: '分析型',
        },
        {
          id: 1,
          name: '定位型-整改类',
        },
        {
          id: 2,
          name: '定位型-关注类',
        },
      ],
      // 建模类型
      modelTypeList: [
        {
          id: 1,
          name: 'SQL建模',
        },
        {
          id: 0,
          name: '数据集建模',
        },
      ],
      // 事件标签数据
      eventTagList: [],

      tableData: [],
      expressions: [
        // <!--  创建人 -->
        {
          dataType: 'str',
          name: 'creatorAccount',
          op: 'eq',
          stringValue: getUserInfo().account,
        },

        //
      ],
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          customRender: (text, record, index) => `${index + 1}`,
        },
        // code name description
        {
          title: '模型名称',
          dataIndex: 'modelName',
        },
        {
          title: '所属分类',
          dataIndex: 'catalogName',
        },
        {
          title: '创建时间',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.date,
        },
        {
          title: '模型共享状态',
          dataIndex: 'shareStatus',
          scopedSlots: { customRender: 'gx' },
        },
        {
          title: '发布状态',
          dataIndex: 'publishStatus',
          scopedSlots: { customRender: 'fb' },
        },
        {
          // reservelong2
          dataIndex: 'reservelong2',
          sdHidden: true,
        },
        {
          title: '操作',
          dataIndex: 'id',
          width: '230px',

          scopedSlots: { customRender: 'edit' },
        },
        // jobName
        {
          title: '跑批任务',
          dataIndex: 'jobName',
          sdHidden: true,
        },
      ],
      actions: [
        {
          label: '搜索',
          permission: null,
          type: TableActionTypes.primary,
          callback: this.tableSearch,
        },
        // 删除
        // {
        //   label: '删除',
        //   id: 'delete',
        //   permission: null,
        //   type: TableActionTypes.batch,
        //   callback: this.tableDelete,
        // },
        {
          label: '自助建模',
          permission: null,
          callback: this.showCreateModel,
        },
      ],
      // 确认保存状态
      rightFlag: false,
    }
  },
  computed: {
    formItemLayout() {
      return {
        layout: 'horizontal',
        labelCol: { span: 4 },
        wrapperCol: { span: 18 },
      }
    },
  },
  created() {
    this.initSelectData()
    this.getModelDomain()
  },

  methods: {
    modelDomainChange(value) {
      this.spaceForm.modelDomainName = this.modelDomainOption.find((item) => item.id === value).name
    },
    // 获取模型领域数据
    getModelDomain() {
      auditMaintainService.getAreaListAll().then((res) => {
        this.modelDomainOption = res.data
      })
    },
    openMessage() {
      message.warning('请进行模型信息完善')
    },

    // 模型编码校验
    validator(rule, value, callback) {
      value = encodeURIComponent(value)
      const url = `api/xcoa-mobile/v1/iammodelmaintain/checkCode?code=${value}`
      debounce(() => {
        axios.post(url).then((res) => {
          if (res.data) {
            callback()
          } else {
            callback('已存在模型编码，不可以重复')
          }
        })
      }, 500)()
    },
    // 模型名称校验
    validatorModelName(rule, value, callback) {
      value = encodeURIComponent(value)
      const url = `api/xcoa-mobile/v1/iammodelmaintain/checkModelName?modelName=${value}`
      debounce(() => {
        axios.post(url).then((res) => {
          if (res.data) {
            callback()
          } else {
            callback('已存在模型名称，不可以重复')
          }
        })
      }, 500)()
    },
    deleteModel(record) {
      // jobName如果是字符类型并且字符长度大于0则提示
      if (record.jobName !== null && record.jobName !== '') {
        Modal.warning({
          title: '提示',
          content: `"${record.modelName}"` + '有跑批任务在执行无法删除此模型 ',
        })
        return
      }
      // 删除
      // 确认是否删除
      Modal.confirm({
        title: '您确定删除这项内容吗？',
        content: '删除这条数据后，就无法恢复初始的状态。',
        cancelText: '取消',
        okText: '删除',
        okType: 'danger',
        onOk: () => {
          auditModelService.deleteModel(record.id).then((res) => {
            message.success('删除成功')
            this.$refs.table.refresh()
          })
        },
        onCancel: () => {},
      })
    },
    handleOk() {
      this.$refs.spaceForm.validate((valid) => {
        if (valid) {
          this.confirmLoading = true
          if (this.rightFlag) {
            return
          }
          // 两秒后可以再次点击
          setTimeout(() => {
            this.rightFlag = false
          }, 2000)
          this.rightFlag = true
          // 关闭弹窗
          const params = {
            ...this.spaceForm,
            datacubeType: this.spaceForm.creatModelType,
          }
          auditModelService.saveModelData(params).then((res) => {
            this.close()
            message.success('保存成功')
            window.open(res.data)
            this.$refs.table.refresh()
            this.confirmLoading = false
            this.rightFlag = false
          })
        }
      })
    },
    close() {
      this.confirmLoading = false
      this.isShowSpace = false
      this.isShowSpace = false
      const filter = ['catalogId', 'source', 'catalogName', 'creatorAccount']
      Object.keys(this.spaceForm).forEach((key) => {
        if (filter.includes(key)) {
          return
        }
        this.spaceForm[key] = null
      })
    },
    // 搜索方法
    handleSearch() {},
    showCreateModel() {
      // 判断是否选择了分类
      if (this.spaceForm.catalogId === null) {
        return message.error('请选择分类')
      }
      this.isShowSpace = !this.isShowSpace
    },
    //
    depChanged(oldId, value) {},
    treeSelect(selectedKeys, info) {
      if (selectedKeys.length === 0) {
        // this.parentId = null
        this.spaceForm.catalogId = null
        this.spaceForm.catalogName = null
        //
        this.expressions = this.expressions.filter((item) => item.name !== 'catalogId')
        return
      }
      const dataRef = info.node.dataRef

      if (dataRef.isroot) {
        this.spaceForm.catalogId = null
        this.spaceForm.catalogName = null
        this.expressions = this.expressions.filter((item) => item.name !== 'catalogId')
      } else {
        this.spaceForm.catalogId = dataRef.id
        this.spaceForm.catalogName = dataRef.categoryName

        //  删除后添加
        this.expressions = this.expressions.filter((item) => item.name !== 'catalogId')

        this.expressions.push({
          dataType: 'str',
          name: 'catalogId',
          op: 'eq',
          stringValue: dataRef.id,
        })
      }
      this.key += 1
    },
    // 表单select值变化
    selectChangeModelType(value) {
      this.spaceForm.modelTypeName = this.modelTypeOption.find((item) => item.id === value).name
    },
    selectChangeEventTag(value) {
      this.spaceForm.eventTagName = this.eventTagList.find((item) => item.id === value).tagName
    },
    initSelectData() {
      // 事件标签
      auditMaintainService.getEventTagList().then((res) => {
        this.eventTagList = res.data
      })
    },
    tableSearch() {},
    tableDelete() {},

    toModel(value, record) {
      // 打开新页面
      if (value === 'class') {
        window.open('#/audit-model-class')
        return
      }
      if (value === 'read') {
        window.open(`#/audit-model-form?record=${record.id}`)
        return
      }
      if (value === 'fb') {
        record.jmTable || message.warning('请获取下发数据表后再发布！')
        record.jmTable && window.open('#/sd-flow-guide?code=PRODUCT_IAM_MLFBSQ&record=' + record.id)
        return
      }
      if (value === 'gx') {
        window.open('#/sd-flow-guide?code=PRODUCT_IAM_MLGXSQ&record=' + record.id)
        return
        // window.open(`#/audit-model-form/${record.id}/gx`)
      }
      // 撤销共享
      if (value === 'cxgx') {
      }
    },
    // 撤销共享
    cancelShare(record) {
      // 确认是否撤销共享
      Modal.confirm({
        title: '您确定撤销共享这项内容吗？',
        cancelText: '取消',
        okText: '撤销共享',
        okType: 'danger',
        onOk: () => {
          auditModelService.revokeShare({ id: record.id }).then((res) => {
            message.success('撤销成功')
            this.$refs.table.refresh()
          })
        },
        onCancel: () => {},
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.wrap-height {
  position: relative;
  display: flex;
  height: 100%;
  .table-right {
    width: calc(100% - 20%);
  }
}
.tree-wrap {
  display: flex;
  align-items: flex-end;
  // 分散布局 水平居中
  justify-content: space-between;
  padding-bottom: 10px;
  margin-top: 10px;
  border-bottom: 1px solid $black;
}
.edit + .edit {
  margin-left: 10px;
  cursor: pointer;
}
</style>
