<template>
  <tf-dialog
    class="standard-save-as"
    v-bind="$attrs"
    v-on="listeners"
    @submit="onSubmit"
    :loading="loading"
    :disabled="loading"
    title="另存为指标标准"
  >
    <el-form label-width="auto" size="small" class="form" ref="form" :model="formData" :rules="rules">
      <el-form-item label="指标标准名称" prop="standardName">
        <el-input v-model="formData.standardName" placeholder="请输入指标标准名称" />
      </el-form-item>
    </el-form>
  </tf-dialog>
</template>

<script lang="ts">
  import { ElForm } from 'element-ui/types/form'
  import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
  import { IStandard, IStandardParam } from '../../api/common'
  import { addStandard, addStandardParam, getStandard, standardPage } from '../../api/standard'
  @Component({ name: 'StandardSaveAs' })
  export default class StandardSaveAs extends Vue {
    @Prop({ type: Object, default: () => ({}) }) standard!: IStandard
    @Prop({ type: Array, default: () => [] }) params!: IStandardParam[]
    @Prop({ type: Number }) typeId!: number
    $refs!: { form: ElForm }
    formData: Partial<IStandard> = { standardName: '' }
    rules: ElForm['rules'] = { standardName: [{ required: true, message: '请输入指标标准名称', trigger: 'change' }] }
    loading: boolean = false

    get listeners() {
      const { submit, ...rest } = this.$listeners
      return rest
    }

    onSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const { id: oldId, standardName: oldName, ...rest } = this.standard

          const saveStandard = async () => {
            try {
              await addStandard({
                standardName: this.formData.standardName,
                typeId: this.typeId,
                ...this.$store.getters['project/info'],
                ...rest
              })
              return true
            } catch (error) {
              console.log(error)
            }
            return false
          }

          const getStandardId = async () => {
            try {
              const {
                result: { records }
              } = await standardPage({ current: 1, size: 1, standardName: this.formData.standardName })
              const { id: standardId } = records[0] || {}
              return standardId
            } catch (error) {
              console.log(error)
            }
            return null
          }

          const saveParams = async (standardId: number) => {
            try {
              const results = await Promise.all(
                this.params.map(({ id, ...rest }) => {
                  return addStandardParam({ standardId, ...rest })
                })
              )

              !results.some((item) => !item) && this.$message.success('指标标准另存成功')
            } catch (error) {
              console.log(error)
            }
          }

          this.loading = true

          const standardSaved = await saveStandard()

          const standardId = standardSaved && (await getStandardId())

          if (standardId && this.params.length > 0) {
            await saveParams(standardId)
          }

          this.loading = false
        }
      })
    }
    @Watch('standard', { immediate: true })
    onStandardChange(standard: IStandard) {
      const { standardName } = standard || {}
      this.formData.standardName = standardName ? `${standardName} - 复制` : ''
    }
  }
</script>

<style lang="scss"></style>
