<template>
  <div class="trialDocumentMenu">
    <div class="menuBox" v-for="item in menu" :key="item.ArchiveTypeEnum">
      <div class="top">
        <i class="el-icon-folder-opened"></i>
        <span>{{ $fd('ArchiveType', item.ArchiveTypeEnum) }}</span>
        <i
          class="el-icon-circle-plus menuAdd"
          :title="$t('trials:trialDocument:menu:add')"
          @click.stop="addMenu(item.ArchiveTypeEnum)"
          v-if="isManage && hasAdd && !viewStatus && item.ArchiveTypeEnum !== 5"
        ></i>
      </div>
      <div
        :class="{ menu: true, selected: menuId === data.Id }"
        v-for="data in item.TrialFileTypeList"
        :key="data.SysFileTypeId"
        @click.stop="handleSelect(data, item.ArchiveTypeEnum)"
      >
        <i class="el-icon-s-order" style="margin-left: 5px"></i>
        <span class="menuItem" :title="isEN ? data.Name : data.NameCN">{{
          isEN ? data.Name : data.NameCN
        }}</span>
        <div
          @click="NATIVE"
          class="menuBtnBox"
          v-if="isManage && hasEdit && !viewStatus"
        >
          <i
            v-if="data.IsSelfDefine"
            class="el-icon-edit-outline"
            :title="$t('trials:trialDocument:menu:edit')"
            @click.stop="editMenu(item.ArchiveTypeEnum, data)"
          />
          <i
            v-if="data.IsSelfDefine"
            class="el-icon-delete"
            :title="$t('trials:trialDocument:menu:del')"
            @click.stop="delMenu(data)"
          />
          <el-switch
            class="menuSwitch"
            @change="(val) => changeIsEnble(val, data)"
            v-model="data.IsEnable"
            :active-value="true"
            :inactive-value="false"
          >
          </el-switch>
        </div>
      </div>
    </div>
    <base-model :config="config">
      <div slot="dialog-body">
        <el-form
          ref="menuForm"
          :model="form"
          label-width="100px"
          size="small"
          :rules="rules"
        >
          <div class="base-dialog-body">
            <el-form-item
              :label="$t('trials:trialDocument:form:ArchiveTypeEnum')"
              prop="ArchiveTypeEnum"
            >
              <el-select
                v-model="form.ArchiveTypeEnum"
                disabled
                placeholder=""
                style="width: 100%"
              >
                <el-option
                  v-for="item in $d.ArchiveType"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              :label="$t('trials:trialDocument:form:Name')"
              prop="Name"
            >
              <el-input v-model="form.Name" />
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div slot="dialog-footer">
        <el-button size="small" @click="canel">
          {{ $t('trials:trialDocument:button:canel') }}
        </el-button>
        <el-button size="small" type="primary" :loading="loading" @click="save">
          {{ $t('trials:trialDocument:button:save') }}
        </el-button>
      </div>
    </base-model>
  </div>
</template>
<script>
import {
  getTrialFileTypeData,
  setAuthorizedView,
  addOrUpdateTrialFileType,
  deleteTrialFileType,
} from '@/api/dictionary'
import baseModel from '@/components/BaseModel'
const defaultForm = () => {
  return {
    ArchiveTypeEnum: null,
    Name: null,
    NameCN: null,
    FirstFinalDate: null,
    IsConfirmRecord: true,
    IsEnable: true,
    IsSelfDefine: true,
    SubIdentificationEnum: null,
    SysFileTypeId: null,
    TrialId: null,
    Id: null,
  }
}
export default {
  name: 'trialDocumentMenu',
  props: {
    viewStatus: {
      type: Boolean,
      default: true,
    },
    menuId: {
      type: String,
      default: '',
    },
    SubIdentificationEnum: {
      type: Number,
      default: 0,
    },
    ArchiveTypeEnum: {
      type: Number,
      default: 0,
    },
    rowData: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      loading: false,
      menu: [],
      config: {
        visible: false,
        showClose: true,
        width: '400px',
        title: '',
        appendToBody: true,
        status: 'add',
      },
      form: defaultForm(),
      rules: {
        Name: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: ['blur', 'change'],
          },
        ],
      },
    }
  },
  components: {
    'base-model': baseModel,
  },
  watch: {
    viewStatus: {
      handler() {
        this.getMenu()
      },
      immediate: true,
    },
  },
  computed: {
    isEN() {
      return this.$i18n.locale !== 'zh'
    },
    isInspect() {
      return this.hasPermi([
        'trials:trials-panel:trial-summary:trial-document:inspect',
      ])
    },
    isManage() {
      return this.hasPermi([
        'trials:trials-panel:trial-summary:trial-document:manage',
      ])
    },
    hasAdd() {
      return this.hasPermi([
        'trials:trials-panel:trial-summary:trial-document:add',
      ])
    },
    hasEdit() {
      return this.hasPermi([
        'trials:trials-panel:trial-summary:trial-document:edit',
      ])
    },
  },
  methods: {
    // 获取菜单
    async getMenu() {
      try {
        let data = {
          TrialId: this.$route.query.trialId,
          IsEnable: this.viewStatus,
        }
        this.loading = true
        let res = await getTrialFileTypeData(data)
        this.loading = false
        if (res.IsSuccess) {
          this.menu = res.Result.TrialFileTypeDataList
          this.$nextTick(() => {
            this.defaultSelect()
          })
        }
      } catch (err) {
        this.loading = false
        console.log(err)
      }
    },
    defaultSelect() {
      if (!this.menu || this.menu.length <= 0) return false
      if (this.menuId) {
        let Id = this.menuId
        let f = this.menu.some((item) => {
          let flag = false
          if (item.TrialFileTypeList && item.TrialFileTypeList.length > 0) {
            flag = item.TrialFileTypeList.some((data) => {
              if (data.Id === Id) {
                this.$emit('update:menuId', null)
                this.$nextTick(() => {
                  this.handleSelect(data, item.ArchiveTypeEnum)
                })
              }
              return data.Id === Id
            })
          }
          return flag
        })
        if (!f) {
          this.$emit('update:menuId', null)
          this.$nextTick(() => {
            this.defaultSelect()
          })
        }
      } else {
        this.menu.some((item) => {
          if (item.TrialFileTypeList && item.TrialFileTypeList.length > 0) {
            this.handleSelect(item.TrialFileTypeList[0], item.ArchiveTypeEnum)
          }
          return item.TrialFileTypeList && item.TrialFileTypeList.length > 0
        })
      }
    },
    // 修改菜单启用
    async changeIsEnble(val, item) {
      try {
        let data = {
          Id: item.Id,
          IsEnable: val,
        }
        this.loading = true
        let res = await setAuthorizedView(data)
        this.loading = false
        if (res.IsSuccess) {
          this.$emit('update:rowData', {})
          this.$nextTick(() => {
            this.$emit('update:rowData', item)
          })
        }
      } catch (err) {
        this.loading = false
        item.IsEnable = !item.IsEnable
        console.log(err)
      }
    },
    // 选中
    handleSelect(data, ArchiveTypeEnum) {
      this.$emit('update:menuId', data.Id)
      this.$emit('update:SubIdentificationEnum', data.SubIdentificationEnum)
      this.$emit('update:ArchiveTypeEnum', ArchiveTypeEnum)
      this.$emit('update:rowData', data)
    },
    // 新增
    addMenu(ArchiveTypeEnum) {
      this.config.title = this.$t('trials:trialDocument:title:add')
      this.form = defaultForm()
      this.form.ArchiveTypeEnum = ArchiveTypeEnum
      this.form.TrialId = this.$route.query.trialId
      switch (ArchiveTypeEnum) {
        case 1: {
          this.form.SubIdentificationEnum = 0
          break
        }
        case 2: {
          this.form.SubIdentificationEnum = 1
          break
        }
        case 3: {
          this.form.SubIdentificationEnum = 2
          break
        }
        case 4: {
          this.form.SubIdentificationEnum = 2
          break
        }
      }
      this.config.visible = true
    },
    // 修改
    editMenu(ArchiveTypeEnum, item) {
      this.config.title = this.$t('trials:trialDocument:title:edit')
      this.form = defaultForm()
      Object.keys(this.form).forEach((key) => {
        this.form[key] = item[key]
      })
      this.form.ArchiveTypeEnum = ArchiveTypeEnum
      this.config.visible = true
    },
    // 删除
    delMenu(row) {
      this.$confirm(this.$t('trials:trialDocument:message:deleteMessage'), {
        type: 'warning',
        distinguishCancelAndClose: true,
      })
        .then(() => {
          this.loading = true
          deleteTrialFileType(row.Id).then((res) => {
            if (res.IsSuccess) {
              this.getMenu()
              this.$message.success(
                this.$t('common:message:deletedSuccessfully')
              )
            }
          })
        })
        .catch((err) => {
          this.loading = false
          console.log(err)
        })
    },
    async save() {
      try {
        let validate = await this.$refs.menuForm.validate()
        if (!validate) return false
        this.form.NameCN = this.form.Name
        this.loading = true
        let res = await addOrUpdateTrialFileType(this.form)
        if (res.IsSuccess) {
          this.config.visible = false
          this.getMenu()
        }
      } catch (err) {
        console.log(err)
        this.loading = false
      }
    },
    canel() {
      this.config.visible = false
    },
    NATIVE(event) {
      event.stopPropagation()
    },
  },
}
</script>
<style lang="scss" scoped>
.trialDocumentMenu {
  padding: 0 10px;
  .menuBox {
    border-bottom: 1px solid rgb(238, 238, 238);
    &:last-child {
      border: none;
    }
    .top {
      color: #303133;
      line-height: 48px;
      width: 100%;
      position: relative;
      i {
        margin-right: 5px;
      }
      .menuAdd {
        margin: 0;
        position: absolute;
        top: 15px;
        right: 0;
        cursor: pointer;
      }
    }
    .menu {
      font-size: 14px;
      margin-bottom: 12px;
      padding: 0 12px 0 20px;
      cursor: pointer;
      min-height: 36px;
      display: flex;
      align-items: center;
      border-radius: 5px;
      position: relative;
      i {
        margin-right: 5px;
      }
      .menuBtnBox {
        position: absolute;
        top: 7px;
        right: 5px;
        display: flex;
        align-items: center;
      }
      .menuItem {
        width: 70%;
        white-space: nowrap; /* 文本不换行 */
        overflow: hidden; /* 超出部分隐藏 */
        text-overflow: ellipsis;
      }
    }
    .menu:hover {
      background: #f5f5f5;
    }
    .menu.selected {
      color: #6698ff;
      background: rgba(102, 152, 255, 0.1);
    }
  }
  .menuSwitch {
    ::v-deep.el-switch__core {
      height: 14px;
      width: 28px !important;
      &::after {
        width: 12px;
        height: 12px;
        top: 0;
      }
    }
  }
  .el-switch.is-checked {
    ::v-deep.el-switch__core {
      height: 14px;
      width: 28px !important;
      &::after {
        margin-left: -12px;
      }
    }
  }
}
</style>