<template>
  <!-- todo 所属分类 cid问题 共享发布按钮显示问题 -->
  <audit-form-top-banner>
    <template slot="afterbtn"> </template>
    <SdDetailForm
      ref="docform"
      form-id="iamModelMaintain"
      page-id="audit/maintain/iamModelMaintain"
      :record-id="this.$route.query.record ? parseInt(this.$route.query.record) : null"
      :read-only="true"
      :class="$style.form"
      @close="close(true)"
      @saved="saved"
    >
      <template v-slot="{ model, fields }">
        <table>
          <tr>
            <td style="padding-left:5px;border:none">
              <audit-advanced-group
                :expand="templateExpand"
                :expand-str="'templateExpand'"
                :group-label="'基本信息'"
                tablestyle="''"
                @changedClick="changedClick"
              ></audit-advanced-group> </td></tr
        ></table>

        <table v-show="templateExpand">
          <tr style="display:none">
            <!-- 模型编号 -->
            <SdFormItemTd name="auditOrgId" />
          </tr>
          <tr>
            <!-- 模型编号 -->
            <!-- <SdFormItemTd name="id" :label="'模型编号'" /> -->
            <SdFormItemTd name="modelCode" :label="'模型编号'" />
            <!-- 模型名称 -->
            <SdFormItemTd name="modelName" />
          </tr>
          <tr>
            <!-- 模型类型 new -->
            <SdFormItemTd
              v-if="modelTypeFocus(fields.modelType.attr.selectListItem, 'init')"
              name="modelType"
            >
              <a-select
                v-model="model.modelType"
                @change="modelTypeChange"
                @focus="modelTypeFocus(fields.modelType.attr.selectListItem)"
              >
                <a-select-option
                  v-for="(item, i) in fields.modelType.attr.selectListItem"
                  :key="i"
                  :value="item.value"
                  >{{ item.label }}</a-select-option
                >
              </a-select>
            </SdFormItemTd>
            <!-- 事件标签 -->
            <SdFormItemTd name="eventTagName" :colspan="1" label="事件标签分类"> </SdFormItemTd>
          </tr>
          <tr>
            <!-- 整改截至时间 ， 状态-->
            <SdFormItemTd name="reformTime" :label="filterType(model, fields)">
              <sd-form-item name="reformTimeType" label=""></sd-form-item>
            </SdFormItemTd>
            <!-- todo 模型下发数据表 -->
            <SdFormItemTd name="viewAddress" />

            <!-- <SdFormItemTd name="jmTable" label="模型下发数据表"> </SdFormItemTd> -->
          </tr>
          <tr>
            <!-- 模型领域， 模型阶段 -->
            <SdFormItemTd name="modelDomainName"> </SdFormItemTd>
            <SdFormItemTd name="modelPhaseName"> </SdFormItemTd>
          </tr>
          <!-- 查看数据地址， 编辑数据地址 -->
          <tr>
            <!-- 是否追责 -->
            <!-- <SdFormItemTd name="isAccountable" /> -->
            <!-- <SdFormItemTd name="editAddress" /> -->
          </tr>
          <tr>
            <!--todo 所属分类 -->
            <SdFormItemTd name="catalogName" label="所属分类"> </SdFormItemTd>
            <SdFormItemTd name="datacubeType" label="建模类型">
              <a-select v-model="model.datacubeType" :disabled="true" @change="cataLogChange">
                <a-select-option v-for="(item, i) in modelTypeList" :key="i" :value="item.id">{{
                  item.name
                }}</a-select-option>
              </a-select>
            </SdFormItemTd>
          </tr>
          <tr>
            <!-- 整改说明 -->
            <SdFormItemTd name="reformDesc" :colspan="3">
              <a-textarea v-model="model.reformDesc" :rows="3" />
            </SdFormItemTd>
          </tr>
          <SdFormItemTd :hidden="true" name="catalogName" />
        </table>

        <table>
          <tr>
            <td style="padding-left:5px;border:none">
              <audit-advanced-group
                :expand="devExpand"
                :expand-str="'devExpand'"
                :group-label="'模型逻辑'"
                @changedClick="changedClick"
              ></audit-advanced-group>
            </td>
          </tr>
        </table>

        <table v-if="devExpand">
          <tr>
            <sd-quill-editor v-model="model.developIdea" :options="editorOption" />
          </tr>
        </table>

        <!-- // 代码逻辑，开发思路，配置思路 -->
        <!-- 每个模块下只有一个 a-textarea -->
        <table>
          <tr>
            <td style="padding-left:5px;border:none">
              <audit-advanced-group
                :expand="codeExpand"
                :expand-str="'codeExpand'"
                :group-label="'代码逻辑'"
                @changedClick="changedClick"
              ></audit-advanced-group>
            </td>
          </tr>
        </table>

        <table v-if="codeExpand">
          <sd-quill-editor v-model="model.codeLogic" :options="editorOption" />
        </table>
      </template>
    </SdDetailForm>
  </audit-form-top-banner>
</template>

<script>
import { Message } from 'ant-design-vue'
import auditFormTopBanner from '@product/iam/components/audit-form-top-banner.vue'
import components from './_import-components/audit-model-form-import'
import SdDetailForm from '@/common/components/sd-detail-form.vue'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import auditMaintainService from '../maintain/audit-maintain-service'
import auditAdvancedGroup from '../../components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '../../components/audit-advanced-group-mixins'
import SdFormItemTd from '@/common/components/sd-form-item-td.vue'
import auditModelService from './audit-model-service'

export default {
  name: 'AuditModelForms',
  metaInfo: {
    title: '模型信息管理',
  },
  components: {
    ...components,
    SdFormItemTd,
    auditAdvancedGroup,
    auditFormTopBanner,
    SdDetailForm,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      regularExpand: true,
      templateExpand: true,
      // 代码逻辑，开发思路，配置思路
      codeExpand: true,
      configExpand: true,
      devExpand: true,
      orgId: '',
      eventList: [],
      // 模型领域 ，模型阶段
      areaOption: [],
      stageOption: [],
      // 所属分类
      catalogOption: [],
      // 分类id
      // 名称
      optionSelect: {
        area: '',
        stage: '',
        event: '',
      },

      flagAll: [],
      allStatus: false,
      // 时间类型
      eventClassOption: [],

      // 是否追责
      isAccountable: false,
      // 刷新表单
      key: 0,
      // 类型option
      typeOption: [],
      // 富文本

      editorOption: {
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'], // toggled buttons
              ['blockquote', 'code-block'],
              [{ header: 1 }, { header: 2 }], // custom button values
              [{ list: 'ordered' }, { list: 'bullet' }],
              [{ script: 'sub' }, { script: 'super' }], // superscript/subscript
              [{ indent: '-1' }, { indent: '+1' }], // outdent/indent
              [{ direction: 'rtl' }], // text direction
              [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
              [{ header: [1, 2, 3, 4, 5, 6, false] }],
              [{ color: [] }, { background: [] }], // dropdown with defaults from theme
              [{ font: [] }],
              [{ align: [] }],
              ['clean'], // remove formatting button
              ['link', 'image'], // link and image, video
            ],
          },
        },
      },
      modelFiled: {},
      times: null,
      modelTypeList: [
        {
          id: 1,
          name: 'SQL建模',
        },
        {
          id: 0,
          name: '数据集建模',
        },
      ],
    }
  },
  computed: {
    isAddStatus() {
      return this.$route.query.record === undefined
    },
  },
  watch: {
    flagAll: {
      handler(val) {
        if (val.length === 2) {
          setTimeout(() => {
            if (this.$refs.docform?.SdForm?.model !== undefined) {
              const {
                modelPhase,
                modelDomain,
                modelDomainName,
                modelPhaseName,
              } = this.$refs.docform.SdForm.model
              if (modelPhase !== null) {
                const stage = this.stageOption.filter((item) => item.id === modelPhase)
                stage.length === 0 &&
                  this.stageOption.push({
                    id: modelPhase,
                    name: modelPhaseName,
                  })
              }
              if (modelDomain !== null) {
                const area = this.areaOption.filter((item) => item.id === modelDomain)
                area.length === 0 &&
                  this.areaOption.push({
                    id: modelDomain,
                    name: modelDomainName,
                  })
              }
            }
            if (this.times) {
              clearTimeout(this.times)
            }
          }, 100)
        }
      },
      deep: true,
    },
  },
  created() {
    if (this.$route.query.orgId) this.orgId = this.$route.query.orgId
    this.getFormOption()
  },
  methods: {
    filterType(model, fields) {
      if (model.reformTimeType === undefined) {
        return '整改截至时间'
      }
      return (
        '整改截至时间(' +
        fields.reformTimeType.attr.selectListItem.find((val) => val.value === model.reformTimeType)
          .label +
        ')'
      )
    },
    openPage(type) {
      const recordId = this.$route.query.record
      type === 'fb' && window.open('#/sd-flow-guide?code=PRODUCT_IAM_MLFBSQ&record=' + recordId)
      type === 'gx' && window.open('#/sd-flow-guide?code=PRODUCT_IAM_MLGXSQ&record=' + recordId)
    },

    getFormOption() {
      auditMaintainService.getEventTagList().then((res) => {
        this.eventList = res.data
      })
      auditMaintainService.getAreaListAll().then((res) => {
        this.areaOption = res.data
        this.flagAll.push(true)
      })
      auditMaintainService.getStageListAll().then((res) => {
        this.stageOption = res.data
        this.flagAll.push(true)
      })
      // 获取全部分类
      auditModelService.getAuditModelTreeAll().then((res) => {
        this.catalogOption = res.data
      })
    },
    modelTypeChange(val) {
      this.isAccountable = val === '1'
      const name = this.typeOption.find((item) => item.value === val).label
      this.$refs.docform.setFieldValue('modelTypeName', name)
    },
    modelTypeFocus(filter, type) {
      this.typeOption = filter
      if (type === 'init') {
        this.$nextTick(() => {
          const val = this.$refs.docform.getFieldValue('modelType')
          const name = this.typeOption.find((item) => item.value === val).label
          this.$refs.docform.setFieldValue('modelTypeName', name)
        })
      }
      return true
    },
    areaChange(val) {
      // 根据val的值过滤选项
      this.optionSelect.area = this.areaOption.find((item) => item.id === val).name
    },
    stageChange(val) {
      this.optionSelect.stage = this.stageOption.find((item) => item.id === val).name
    },
    // 事件标签变化
    eventChange(val) {
      this.optionSelect.event = this.eventList.find((item) => item.id === val).tagName
    },
    cataLogChange(val) {
      this.$refs.docform.setFieldValue('catalogId', val)
      this.$refs.docform.setFieldValue(
        'catalogName',
        this.catalogOption.find((item) => item.id === val).categoryName
      )
    },

    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.fullPath, flag)
      window.close()
    },
    // 保存
    saveForm() {
      if (this.orgId !== '') {
        this.$refs.docform.setFieldValue('auditOrgId', parseInt(this.orgId))
      }
      // 是否增加名字
      const { area, stage, event } = this.optionSelect
      area !== '' && this.$refs.docform.setFieldValue('modelDomainName', area)
      stage !== '' && this.$refs.docform.setFieldValue('modelPhaseName', stage)
      event !== '' && this.$refs.docform.setFieldValue('eventTagName', event)
      //
      // reservelong2 :1
      this.$refs.docform.setFieldValue('reservelong2', 1)

      this.$refs.docform.validateFields().then(() => {
        this.$refs.docform.saveBtnClick()
      })
    },
    saved() {
      Message.success({ content: '保存成功！' }, 1).then(() => {
        // this.close(true)
        window.close()
      })
    },

    initParam(model) {
      // 设置父id
      const catalogId = this.$route.query.catalogId
      const catalogName = this.$route.query.catalogName
      if (catalogId) {
        model.catalogId = Number(catalogId)
      }
      if (catalogName) {
        model.catalogName = catalogName
      }
    },
    createEditor() {
      // 创建编辑器
      // const editor3 = new wangEditor('#editor3')
      // editor3.config.height = 500
      // this.editor3 = editor3
      // editor3.create()
      // editor3.txt.html('<p>用 JS 设置的内容</p>')
      return true
    },
    setModelFiled(model) {
      this.modelFiled = model
      this.flagAll.push(true)
    },
  },
}
</script>

<style module lang="scss">
@import '@/webflow/sd-flow-form.scss';
.btns button {
  top: 8px;
  float: right;
  margin-right: 10px;
  font-size: 16px;
  font-weight: 400;
  cursor: pointer;
}
</style>

<style>
.reform-time-maintain-from {
  display: flex;
}
.reform-time-data {
  margin-top: 4px;
}
</style>
