<template>
  <sd-form ref="form" :init-values="fields">
    <template v-slot="{ model }">
      <table class="sd-form-table">
        <tr v-for="field in fields" v-show="!field.sdHidden" :key="field.name">
          <sd-form-item-td :name="field.name">
            <!-- 消息接收人 -->
            <template v-if="field.name === 'receiverFormula'">
              <sd-formula-compute
                v-model="dataSource.receiverFormulaFD"
                :load-fields="loadFormulaFields"
                data-type="user[]"
                @update="
                  ($event) => {
                    $set(model, field.name, $event)
                    valueChange($event, field.name)
                  }
                "
              />
            </template>
            <!-- 消息内容 -->
            <sd-formula-compute
              v-if="field.name === 'msgContent'"
              v-model="dataSource[field.name + 'FormulaFD']"
              :load-fields="loadFormulaFields"
              data-type="string"
              @update="
                ($event) => {
                  $set(model, field.name, $event)
                  valueChange($event, field.name)
                }
              "
            />
            <!-- 消息类型 -->
            <a-select
              v-if="field.name === 'msgType'"
              v-model="dataSource[field.name]"
              :options="notifyOptions"
              mode="multiple"
              @change="(value) => valueChange(value, field.name)"
            />
            <!-- 待阅表单 -->
            <sd-list-picker
              v-if="field.name === 'informForm'"
              v-model="model[field.name]"
              single
              :load-list-data="loadOnlineFormListPickerData"
              @change="(value) => valueChange(value, field.name)"
            />
            <!-- 关联条件 -->
            <sd-associate-conditions
              v-if="field.name === 'associateConditions'"
              v-model="dataSource.associateConditions"
              :dest-form-id="model.informForm && model.informForm[0] && model.informForm[0].id"
              :src-form-id="SdEventsManage.formId"
              dest-placeholder="待阅表单字段"
              @change="(value) => valueChange(value, field.name)"
            />
          </sd-form-item-td>
        </tr>
      </table>
    </template>
  </sd-form>
</template>

<script>
import axios from '@/common/services/axios-instance'
import ApplicationService from '@/application-manage/application-service'
import components from './_import-components/sd-message-remind-import'

export const metaInfo = {
  name: '消息提醒',
  order: 300,
  // 标签：对事件处理器进行描述。create：创建消息提醒
  tags: ['create'],
}

export default {
  name: 'SdMessageRemind',
  components,
  data() {
    return {
      fields: [
        {
          name: 'receiverFormula',
          caption: '消息接收人',
          dataType: 'string',
          required: true,
        },
        {
          name: 'msgContent',
          caption: '消息内容',
          dataType: 'string',
          required: true,
        },
        {
          name: 'msgType',
          caption: '消息类型',
          dataType: 'string',
          required: true,
        },
        {
          name: 'sendInform',
          caption: '发待阅',
          dataType: 'string',
          sdHidden: true,
        },
        {
          name: 'informForm',
          caption: '待阅表单',
          dataType: 'string',
          required: true,
          attr: {
            displayExpr: '#bean.sendInform == "1"',
          },
        },
        {
          name: 'associateConditions',
          caption: '关联条件',
          dataType: 'string',
          required: true,
          attr: {
            displayExpr: '#bean.sendInform == "1"',
          },
        },
      ],
      formulaFieldsMap: {},
      notifyOptions: [],
    }
  },
  created() {
    // 获取消息类型
    this.loadMessageTypes()
    // 编辑时
    if (Object.keys(this.dataSource).length > 0) {
      this.fields.forEach((f) => {
        const value = this.dataSource[f.name]
        if (['informForm', 'associateConditions'].includes(f.name)) {
          // 待阅表单、关联条件
          f.value = typeof value === 'object' ? JSON.stringify(value) : undefined
        } else if (f.name === 'msgType') {
          // 消息类型
          f.value = value?.toString()
        } else if (f.name === 'sendInform') {
          // 消息类型包含发待阅
          f.value = this.dataSource.msgType?.includes('inform') ? '1' : '0'
        } else {
          f.value = value
        }
      })
    }
  },
  methods: {
    validate() {
      return this.$refs.form.validateFields()
    },
    valueChange(value, field) {
      if (field === 'msgType') {
        const hasInform = value?.includes('inform')
        this.$refs.form.setFieldsValue({
          [field]: value?.toString(),
          sendInform: hasInform ? '1' : '0',
        })
        // 消息类型，不包含待阅，清空待阅表单和关联条件
        if (!hasInform && this.dataSource.informForm?.[0]) {
          this.$refs.form.setFieldsValue({ informForm: undefined, associateConditions: undefined })
          this.$delete(this.dataSource, 'informForm')
          this.$delete(this.dataSource, 'associateConditions')
        }
      } else if (field === 'associateConditions') {
        const v = value?.filter((c) => c.destColumn?.[0] && c.srcColumn?.[0])
        this.$refs.form.setFieldValue('associateConditions', v?.length > 0 ? v : undefined)
      } else {
        this.$set(this.dataSource, field, value)
      }
      // 消息接收人、消息内容变更，触发校验
      if (['receiverFormula', 'msgContent'].includes(field)) {
        this.$refs.form.validateField(field)
      }
    },
    loadFormulaFields(dataTypes) {
      const formId = this.SdEventsManage.formId
      if (!this.formulaFieldsMap[formId]) {
        return ApplicationService.getOnlFormFieldsById(formId).then((fields) => {
          this.formulaFieldsMap[formId] = fields
          return fields
        })
      }
      return Promise.resolve(this.formulaFieldsMap[formId])
    },
    loadOnlineFormListPickerData() {
      return ApplicationService.getOnlFormListData(this.SdEventsManage.appId, 1)
    },
    loadMessageTypes() {
      axios
        .get('api/framework/v1/dict-manager/dictvalues', {
          params: { keyId: 'PLATFORM_MESSAGE_TYPE' },
        })
        .then((res) => {
          this.notifyOptions = res.data?.map((d) => ({ value: d.id, label: d.name }))
        })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
</style>
