<template>
  <BaseContainer>
    <!-- 搜索框 -->
    <template slot="search-container">
      <el-form :inline="true" size="mini">
        <el-form-item label="器官类型">
          <el-select v-model="searchData.OrganType" clearable style="width:130px;">
            <el-option v-for="item of CriterionDictionaryOrganTypeList.OrganType" :key="item.Id" :value="parseInt(item.Code)" :label="item.ValueCN" />
          </el-select>
        </el-form-item>
        <el-form-item label="部位">
          <el-input v-model="searchData.Part" clearable style="width:130px;" />
        </el-form-item>
        <el-form-item label="器官">
          <el-input v-model="searchData.TULOC" clearable style="width:130px;" />
        </el-form-item>
        <el-form-item label="是否淋巴结">
          <el-select v-model="searchData.IsLymphNodes" clearable style="width:130px;">
            <el-option v-for="item of $d.ReadingYesOrNo" :key="item.id" :value="item.value" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <!-- 查询 -->
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSearch">
            {{ $t('common:button:search') }}
          </el-button>
          <!-- 重置 -->
          <el-button type="primary" icon="el-icon-refresh-left" size="mini" @click="handleReset">
            {{ $t('common:button:reset') }}
          </el-button>
        </el-form-item>
      </el-form>
      <span style="margin-left:auto">
        <!-- 设置 -->
        <el-button
          v-if="!isCompleteConfig"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleSet"
        >
          {{ $t('trials:readingUnit:baseDataCfg:button:set') }}
        </el-button>
        <!-- <el-button

          type="primary"
          size="mini"
          @click="lesionType.visible = true"
        >
          病灶类型配置
        </el-button> -->
        <el-button
          type="primary"
          size="mini"
          @click="lesionType.visible = true"
        >
          病灶关联配置
        </el-button>
        <!--        <el-button-->
        <!--          v-if="!isCompleteConfig"-->
        <!--          type="primary"-->
        <!--          size="mini"-->
        <!--          @click="handleSet"-->
        <!--        >-->
        <!--          默认数据配置-->
        <!--        </el-button>-->
        <el-button
          v-if="!isCompleteConfig"
          type="primary"
          size="mini"
          @click="handleAdd"
        >
          {{ $t('common:button:new') }}
        </el-button>
      </span>

    </template>

    <template slot="main-container">
      <!-- 受试者列表 -->
      <el-table
        ref="organList"
        v-loading="loading"
        v-adaptive="{bottomOffset:60}"
        :data="list"
        stripe
        height="100"
        @sort-change="handleSortByColumn"
      >
        <el-table-column type="index" width="90" />
        <!-- 类型 -->
        <el-table-column
          prop="OrganType"
          label="器官类型"
          min-width="120"
          show-overflow-tooltip
          sortable="custom"
        >
          <template slot-scope="scope">
            {{ $fd('OrganType',scope.row.OrganType) }}
          </template>

        </el-table-column>
        <el-table-column
          prop="Classification"
          label="分类"
          show-overflow-tooltip
          sortable="custom"
        />
        <el-table-column
          prop="ClassificationEN"
          label="分类（英文）"
          min-width="140"
          show-overflow-tooltip
          sortable="custom"
        />
        <!-- 部位 -->
        <el-table-column
          prop="Part"
          label="部位"
          show-overflow-tooltip
          sortable="custom"
        />
        <el-table-column
          prop="PartEN"
          label="部位（英文）"
          min-width="140"
          show-overflow-tooltip
          sortable="custom"
        />
        <el-table-column
          prop="TULOC"
          label="器官"
          show-overflow-tooltip
          sortable="custom"
        />
        <el-table-column
          prop="TULOCEN"
          label="器官（英文）"
          min-width="140"
          show-overflow-tooltip
          sortable="custom"
        />
        <el-table-column
          prop="TULAT"
          label="位置"
          show-overflow-tooltip
          sortable="custom"
        />
        <el-table-column
          prop="TULATEN"
          label="位置（英文）"
          min-width="140"
          show-overflow-tooltip
          sortable="custom"
        />
        <el-table-column
          prop="IsLymphNodes"
          label="是否淋巴结"
          min-width="160"
          show-overflow-tooltip
          sortable="custom"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.IsLymphNodes" type="danger">
              {{ $fd('ReadingYesOrNo', scope.row.IsLymphNodes) }}
            </el-tag>
            <el-tag v-else type="primary">{{ $fd('ReadingYesOrNo', scope.row.IsLymphNodes) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="IsCanEditPosition"
          label="是否可以编辑"
          min-width="160"
          show-overflow-tooltip
          sortable="custom"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.IsCanEditPosition" type="danger">
              {{ $fd('YesOrNo', scope.row.IsCanEditPosition) }}
            </el-tag>
            <el-tag v-else type="primary">{{ $fd('YesOrNo', scope.row.IsCanEditPosition) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="ShowOrder"
          label="序号"
          show-overflow-tooltip
          min-width="80"
        />
        <el-table-column
          prop="Remark"
          label="备注"
          show-overflow-tooltip
        />

        <el-table-column
          v-if="!isCompleteConfig"
          :label="$t('common:action:action')"
          width="120"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              circle
              title="编辑"
              icon="el-icon-edit-outline"
              @click="handleEdit(scope.row)"
            />
            <el-button
              circle
              title="删除"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize" @pagination="getList" />
    </template>

    <!-- 新增/编辑 -->
    <el-dialog
      v-if="editDialog.visible"
      :visible.sync="editDialog.visible"
      :close-on-click-modal="false"
      :title="editDialog.title"
      width="500px"
      custom-class="base-dialog-wrapper"
      append-to-body
    >
      <OrganForm
        :data="rowData"
        :criterion-id="criterionId"
        @close="editDialog.visible = false"
        @getList="getList"
      />
    </el-dialog>

    <!-- 病灶类型 -->
    <el-dialog
      v-if="lesionType.visible"
      :visible.sync="lesionType.visible"
      :close-on-click-modal="false"
      :title="lesionType.title"
      width="800px"
      custom-class="base-dialog-wrapper"
      append-to-body
    >
      <LesionTypeTbl
        :criterion-id="criterionId"
        :is-complete-config="isCompleteConfig"
        @close="lesionType.visible = false"
      />
    </el-dialog>

    <!-- 选择标准 -->
    <el-dialog
      v-if="criterion.visible"
      :visible.sync="criterion.visible"
      :close-on-click-modal="false"
      :title="criterion.title"
      width="500px"
      custom-class="base-dialog-wrapper"
      append-to-body
    >
      <el-form
        ref="criterionForm"
        v-loading="formLoading"
        :model="form"
        size="small"
      >
        <div class="base-dialog-body">
          <!-- 类型 -->
          <el-form-item
            label="标准"
            prop="CriterionId"
            :rules="[
              { required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur'] },
            ]"
          >
            <el-select
              v-model="form.CriterionId"
            >
              <el-option
                v-for="item of criterions"
                :key="item.CriterionId"
                :label="item.CriterionName"
                :value="item.CriterionId"
                :disabled="criterionId === item.CriterionId"
              />
            </el-select>
          </el-form-item>
        </div>
        <div class="base-dialog-footer" style="text-align:right;margin-top:10px;">
          <el-form-item style="text-align:right;">
            <el-button type="primary" @click="criterion.visible = false"> {{ $t('common:button:cancel') }}</el-button>
            <el-button size="small" type="primary" @click="handleSave">
              {{ $t('common:button:save') }}
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-dialog>
  </BaseContainer>
</template>
<script>
import { getOrganPageList, deleteOrganInfo, getCriterionNidusList, copySystemCriterionData, synchronizeSystemOrgan, getCriterionDictionary } from '@/api/dictionary'
import { getSystemCriterionList, synchronizeSystemOrganToTrial } from '@/api/trials'
import BaseContainer from '@/components/BaseContainer'
import Pagination from '@/components/Pagination'
import OrganForm from './OrganForm'
import LesionTypeTbl from './LesionTypeTbl'
const searchDataDefault = () => {
  return {
    SystemCriterionId: '',
    OrganType: null,
    PageIndex: 1,
    PageSize: 20,
    TULOC: null,
    TULAT: null,
    IsLymphNodes: null
  }
}
export default {
  name: 'OrgansList',
  components: { BaseContainer, Pagination, OrganForm, LesionTypeTbl },
  props: {
    criterionId: {
      type: String,
      required: true
    },
    isCompleteConfig: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      searchData: searchDataDefault(),
      loading: false,
      list: [],
      total: 0,
      rowData: {},
      editDialog: { title: '', visible: false },
      lesionType: { title: '病灶器官关联关系', visible: false },
      // lesionTypes: [],
      criterion: { title: '默认数据配置', visible: false },
      formLoading: false,
      form: { CriterionId: '' },
      criterions: [],
      CriterionDictionaryOrganTypeList: null
    }
  },
  watch: {
    list() {
      this.$nextTick(() => {
        if(!this.$refs.organList) return
        this.$refs.organList.doLayout()
      })
    }
  },
  mounted() {
    this.getCriterions()
    this.getList()
    this.getCriterionDictionaryOrganType()
  },
  methods: {
    getCriterionDictionaryOrganType() {
      getCriterionDictionary({
        ReadingCriterionId: this.criterionId,
        DictionaryCode: 'OrganType'
      }).then(res => {
        this.CriterionDictionaryOrganTypeList = res.Result
      })
    },
    synchronizeSystemOrganToTrial() {
      this.loading = true
      synchronizeSystemOrganToTrial({
        TrialReadingCriterionId: this.criterionId
      }).then(res => {
        this.loading = false
        this.$message.success('同步成功')
      }).catch(() => {
        this.loading = false
      })
    },
    // 获取受试者列表
    getList() {
      this.loading = true
      this.searchData.SystemCriterionId = this.criterionId
      getOrganPageList(this.searchData).then(res => {
        this.loading = false
        // this.list = res.Result
        this.list = res.Result.CurrentPageData
        this.total = res.Result.TotalCount
      }).catch(() => { this.loading = false })
    },
    getLesionTypes() {
      return new Promise((resolve, reject) => {
        getCriterionNidusList({ criterionId: this.criterionId }).then(res => {
          this.lesionTypes = res.Result
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },
    // 新增
    handleAdd() {
      this.rowData = { SystemCriterionId: this.criterionId }
      this.editDialog.title = '新增'
      this.editDialog.visible = true
    },
    // 编辑
    handleEdit(row) {
      this.rowData = { ...row }
      this.editDialog.title = '编辑'
      this.editDialog.visible = true
    },
    // 删除
    handleDelete(row) {
      this.$confirm('是否确认删除', {
        type: 'warning',
        distinguishCancelAndClose: true
      })
        .then(() => {
          this.loading = true
          deleteOrganInfo(row.Id)
            .then(res => {
              this.loading = false
              if (res.IsSuccess) {
                this.getList()
                this.$message.success('删除成功！')
              }
            }).catch(() => { this.loading = false })
        })
    },
    getCriterions() {
      getSystemCriterionList().then(res => {
        this.criterions = res.Result
      })
    },
    // 查询
    handleSearch() {
      this.searchData.PageIndex = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.searchData = searchDataDefault()
      this.getList()
    },
    // 排序
    handleSortByColumn(column) {
      if (column.order === 'ascending') {
        this.searchData.Asc = true
      } else {
        this.searchData.Asc = false
      }
      this.searchData.SortField = column.prop
      this.searchData.PageIndex = 1
      this.getList()
    },
    handleSet() {
      this.criterion.visible = true
      this.form.CriterionId = ''
    },
    handleSave() {
      this.$refs['criterionForm'].validate((valid) => {
        if (!valid) return
        this.formLoading = true
        var param = {
          FromCriterionId: this.form.CriterionId,
          ToCriterionId: this.criterionId
        }
        synchronizeSystemOrgan(param).then(res => {
          this.getList()
          this.criterion.visible = false
          this.formLoading = false
        }).catch(() => {
          this.formLoading = false
        })
      })
    }
  }
}
</script>
