<template>
  <audit-form-top-banner>
    <template slot="afterbtn">
      <div :class="$style.btns">
        <a-button type="primary" :disabled="!showPublish" @click="openPage('fb')">发布</a-button>
        <a-button type="primary" :disabled="!showShare" @click="openPage('gx')">共享</a-button>
        <!-- 开启调度 -->
        <a-button type="primary" @click="checkPublish('dd')">开始调度</a-button>
        <a-button type="primary" @click="saveForm">保存</a-button>
      </div>
    </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="this.$route.query.type === 'readonly'"
      :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="模型编号" :input-props="{ disabled: true }" /> -->
            <SdFormItemTd name="modelCode" label="模型编号" :input-props="{ disabled: true }" />
            <!-- 模型名称 -->
            <SdFormItemTd name="modelName">
              <a-form-model-item
                :rules="[
                  {
                    validator: validatorModelName,
                    trigger: ['blur'],
                  },
                ]"
                prop="modelName"
              >
                <a-input v-model="model.modelName" />
              </a-form-model-item>
            </SdFormItemTd>
          </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="eventTag" :colspan="1" label="事件标签分类">
              <a-select v-model="model.eventTag" @change="eventChange">
                <a-select-option v-for="(item, i) in eventList" :key="i" :value="item.id">{{
                  item.tagName + '-' + item.id
                }}</a-select-option>
              </a-select>
            </SdFormItemTd>
          </tr>
          <tr>
            <!-- 整改截至时间 ， 状态-->
            <SdFormItemTd name="reformTime" label="整改截至时间">
              <div class="reform-time-maintain-from">
                <a-input-number
                  v-model="model.reformTime"
                  :min="minSize"
                  :disabled="model.modelType !== '1'"
                  class="reform-time-data"
                ></a-input-number>

                <sd-form-item name="reformTimeType" label=""></sd-form-item>
              </div>
            </SdFormItemTd>
            <SdFormItemTd name="jmTable" label="模型下发数据表"> </SdFormItemTd>
          </tr>
          <tr>
            <!-- 模型领域， 模型阶段 -->
            <SdFormItemTd name="modelDomain">
              <a-select v-model="model.modelDomain" :disabled="true" @change="areaChange">
                <a-select-option v-for="(item, i) in areaOption" :key="i" :value="item.id">{{
                  item.name
                }}</a-select-option>
              </a-select>
            </SdFormItemTd>
            <SdFormItemTd name="modelPhase">
              <a-select v-model="model.modelPhase" @change="stageChange">
                <a-select-option v-for="(item, i) in stageOption" :key="i" :value="item.id">{{
                  item.name
                }}</a-select-option>
              </a-select>
            </SdFormItemTd>
          </tr>
          <!-- 查看数据地址， 编辑数据地址 -->
          <tr>
            <SdFormItemTd name="viewAddress">
              <a-button type="primary" :disabled="!model.jmId" @click="onViewJm(model.jmId)"
                >查看</a-button
              >
            </SdFormItemTd>
            <!-- 是否追责 -->
            <!-- <SdFormItemTd name="isAccountable" /> -->
            <!-- <SdFormItemTd name="editAddress" /> -->
          </tr>
          <tr>
            <SdFormItemTd name="catalogId" label="所属分类">
              <a-select v-model="model.catalogId" :disabled="true" @change="cataLogChange">
                <a-select-option v-for="(item, i) in catalogOption" :key="i" :value="item.id">{{
                  item.categoryName
                }}</a-select-option>
              </a-select>
            </SdFormItemTd>
          </tr>
          <tr>
            <!-- 整改说明 -->
            <SdFormItemTd name="reformDesc" :colspan="3">
              <a-textarea v-model="model.reformDesc" :rows="3" />
            </SdFormItemTd>
          </tr>
          <tr>
            <SdFormItemTd name="risk" label="风险描述" :colspan="3">
              <a-textarea v-model="model.risk" :rows="3" />
            </SdFormItemTd>
          </tr>
          <SdFormItemTd :hidden="true" name="catalogName" />
        </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>

        <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>

        <table>
          <tr>
            <td style="padding-left:5px;border:none">
              <audit-advanced-group
                :expand="configExpand"
                :expand-str="'configExpand'"
                :group-label="'配置思路'"
                @changedClick="changedClick"
              ></audit-advanced-group>
            </td>
          </tr>
        </table> -->

        <table v-if="configExpand">
          <tr>
            <sd-quill-editor v-model="model.configIdea" :options="editorOption" />
          </tr>
        </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'
import debounce from 'lodash.debounce'
import axios from '@/common/services/axios-instance'

export default {
  name: 'AuditModelForm',
  metaInfo: {
    title: '模型信息管理',
  },
  components: {
    ...components,
    SdFormItemTd,
    auditAdvancedGroup,
    auditFormTopBanner,
    SdDetailForm,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      templateExpand: true,
      // 代码逻辑，开发思路，配置思路
      codeExpand: true,
      configExpand: true,
      devExpand: true,
      orgId: '',
      // 是否显示发布，或者共享按钮
      showPublish: false,
      showShare: false,
      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,
    }
  },
  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) {
                const stage = this.stageOption.filter((item) => item.id === modelPhase)
                stage.length === 0 &&
                  this.stageOption.push({
                    id: modelPhase,
                    name: modelPhaseName,
                  })
              }
              if (modelDomain) {
                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: {
    // 模型名称校验
    validatorModelName(rule, value, callback) {
      value = encodeURIComponent(value)
      const modelId = this.$route.query.record ? `&id=${this.$route.query.record}` : ''
      const url = `api/xcoa-mobile/v1/iammodelmaintain/checkModelName?modelName=${value}` + modelId
      debounce(() => {
        axios.post(url).then((res) => {
          if (res.data) {
            callback()
          } else {
            callback('已存在模型名称，不可以重复')
          }
        })
      }, 500)()
    },
    onViewJm(id) {
      if (!id) return
      auditModelService.getBuildUrl(id).then((res) => {
        if (res.data) {
          window.open(res.data)
        }
      })
    },
    openPage(type) {
      const recordId = this.$route.query.record
      type === 'fb' && this.checkPublish(type, recordId)
      type === 'gx' && window.open('#/sd-flow-guide?code=PRODUCT_IAM_MLGXSQ&record=' + recordId)
    },
    // 校验发布 如果模型下发数据表没有数据则不能发布 并提示请重新获取下发数据表后再发布
    checkPublish(type, recordId) {
      if (type === 'dd') {
        auditModelService.triggerModel().then(() => {
          Message.success({ content: '已开始调度,请稍后刷新页面后重试' })
        })
        return
      }
      const { jmTable } = this.$refs.docform.SdForm.model
      if (!jmTable) {
        Message.warning({ content: '请开启调度获取模型下发数据表数据' })
        return false
      }
      type === 'fb' && window.open('#/sd-flow-guide?code=PRODUCT_IAM_MLFBSQ&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
      })
      // 获取模型列表详情
      if (this.$route.query.record) {
        const data = {
          columns:
            'sortNumber,modelName,catalogName,creationTime,shareStatus,publishStatus,reservelong2,id',
          maxResults: 10,
          startPosition: 0,
          expressions: [
            {
              dataType: 'str',
              name: 'id',
              op: 'eq',
              stringValue: this.$route.query.record,
            },
          ],
          buttonExpressions: [],
        }
        auditModelService.getModelListDetail(data).then((res) => {
          if (res.data.data.length > 0) {
            const { publishStatus, shareStatus } = res.data.data[0]
            this.showPublish = publishStatus === null
            this.showShare = shareStatus === null
          }
        })
      }
    },
    modelTypeChange(val) {
      this.isAccountable = val === '1'
      const name = this.typeOption.find((item) => item.value === val).label
      this.$refs.docform.setFieldValue('modelTypeName', name)
      // reformTime
      if (val !== '1') {
        this.$refs.docform.setFieldValue('reformTime', 0)
        this.minSize = 0
      } else {
        this.$refs.docform.setFieldValue('reformTime', 1)
        this.minSize = 1
      }
    },
    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)
          const reformTime = this.$refs.docform.getFieldValue('reformTime')
          if (!reformTime) {
            this.$refs.docform.setFieldValue('reformTime', 0)
          }
        })
      }
      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>
