<template>
  <div>
    <a-form layout='vertical'>
      <a-spin :spinning="loading">
        <a-tabs v-model="tabName" type="card">
          <a-tab-pane
              :tab="$t('functional-analysis.property-modal.name')"
              key="name">
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.language')">
                  <a-select
                      @change="currentNlsChange"
                      :defaultValue="defaultNls">
                    <a-select-option
                        v-for="(item, index) in currentNls"
                        :key="index"
                        :value="item.lkey">
                      {{ $t('global-dict.select-nls.' + item.lkey) }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item required :label="$t('functional-analysis.property-modal.name')">
                  <a-input v-model="name" :maxLength="1000" @change="nameChange"/>
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>
          <a-tab-pane
              :tab="$t('functional-analysis.property-modal.rating')"
              key="evaluate">
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.occurrence')">
                  <a-input-number
                      v-model="occurrenceInputVal"
                      :min="1"
                      :max="10"
                      @change="occurrenceInputValChange"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-table
                :data-source="occurrenceTableData"
                :columns="occurrenceTableColumns"
                :customRow="occurrenceCustomRow"
                class="evaluate"
                :rowKey="(row, index) => {return index;}"
                :row-selection="{
                type: 'radio',
                selectedRowKeys: occurrenceSelectedRowKeys,
                onChange: occurrenceRadioChange,
              }"
                bordered
                size="small"
                :scroll="{ y: 'calc(88vh - 400px)' }"
                :pagination="false">
            </a-table>
          </a-tab-pane>
          <a-tab-pane
              :tab="$t('functional-analysis.property-modal.characteristic')"
              key="characteristic">
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="'\xa0'">
                  <a-checkbox
                      :checked="inFmeaFlag === '1'"
                      @change="inFmeaFlagChange">
                    {{ $t('functional-analysis.property-modal.included-in-fmea-form') }}
                  </a-checkbox>
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>
          <a-tab-pane
              :tab="$t('functional-analysis.property-modal.test')"
              key="test">
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.language')">
                  <a-select
                      @change="testCurrentNlsChange"
                      :defaultValue="defaultNls">
                    <a-select-option
                        v-for="(item, index) in currentNls"
                        :key="index"
                        :value="item.lkey">
                      {{ $t('global-dict.select-nls.' + item.lkey) }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.test-name')">
                  <a-input disabled v-model="test.testName" :maxLength="1000" @change="nameChange"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.test-method')">
                  <a-textarea
                      :placeholder="$t('functional-analysis.property-modal.click-to-enter-test-method')"
                      allowClear
                      v-model="test.testMethod"
                      :autoSize="{ minRows: 5 }"
                      :maxLength="1000"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.acceptance-criteria')">
                  <a-textarea
                      :placeholder="$t('functional-analysis.property-modal.click-to-enter-the-acceptance-criteria')"
                      allowClear
                      v-model="test.testStandard"
                      :autoSize="{ minRows: 5 }"
                      :maxLength="1000"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.test-location')">
                  <a-textarea
                      :placeholder="$t('functional-analysis.property-modal.click-to-enter-test-location')"
                      allowClear
                      v-model="test.testPlace"
                      :autoSize="{ minRows: 5 }"
                      :maxLength="1000"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.sampling-coverage')">
                  <a-textarea
                      :placeholder="$t('functional-analysis.property-modal.click-to-enter-sampling-coverage')"
                      allowClear
                      v-model="test.sampleRange"
                      :autoSize="{ minRows: 5 }"
                      :maxLength="1000"/>
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>
          <a-tab-pane
              :tab="$t('functional-analysis.property-modal.analysis')"
              key="analysis">
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.language')">
                  <a-select
                      @change="analysisNlsChange"
                      :defaultValue="defaultNls">
                    <a-select-option
                        v-for="(item, index) in currentNls"
                        :key="index"
                        :value="item.lkey">
                      {{ $t('global-dict.select-nls.' + item.lkey) }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.preventive-measure')">
                  <a-input v-model="analysis.analysisName" :maxLength="500" disabled/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.analysis-request-number')">
                  <a-input v-model="analysis.analysisRequestNo" :maxLength="500" @change="(val) => {
                    analysisChange(val,'analysisRequestNo')}"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.objective')">
                  <a-input v-model="analysis.goal" :maxLength="500" @change="(val) => {
                    analysisChange(val,'goal')}"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.analysis-description')">
                  <a-input v-model="analysis.analysisDescription" :maxLength="500" @change="(val) => {
                    analysisChange(val,'analysisDescription')}"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.confidence-of-analytical-models')">
                  <a-select v-model="analysis.confidenceLevel" @change="(val) => {
                    analysisChange(val,'confidenceLevel')}">
                    <a-select-option
                        v-for="item in confidenceLevel"
                        :key="item.key"
                        :value="item.key">
                      {{ item.value }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.new-acceptance-criteria')">
                  <a-input v-model="analysis.acceptanceCriteria" :maxLength="500" @change="(val) => {
                    analysisChange(val,'acceptanceCriteria')}"/>
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>
          <a-tab-pane
              :tab="$t('functional-analysis.property-modal.repair')"
              key="repair">
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.maintenance-cycle')">
                  <a-range-picker
                      :value="repair.maintenanceCycle"
                      allow-clear
                      class="width100"
                      @change="closeDateChange"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.maintenance-methods')">
                  <a-textarea
                      :placeholder="$t('functional-analysis.property-modal.please-enter-maintenance-methods')"
                      allowClear
                      v-model="repair.maintenanceMethod"
                      :autoSize="{ minRows: 5 }"
                      :maxLength="1000"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.acceptance-standard')">
                  <a-textarea
                      :placeholder="$t('functional-analysis.property-modal.please-enter-acceptance-standard')"
                      allowClear
                      v-model="repair.acceptanceStandard"
                      :autoSize="{ minRows: 5 }"
                      :maxLength="1000"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.maintenance-frequency')">
                  <a-select @change="frequencyChange" :value="repair.maintenanceFrequency" allowClear :placeholder="$t('functional-analysis.property-modal.please-select-maintenance-frequency')">
                    <a-select-option
                        v-for="(item, index) in maintenanceFrequencyDict"
                        :key="index"
                        :value="item.key">
                      {{ item.value }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>
          <a-tab-pane
              :tab="$t('functional-analysis.property-modal.responsible-person')"
              key="responsible">
            <a-table
                :data-source="responsibleTableData"
                :columns="responsibleTableColumns"
                :customRow="distributeStatus == 1 ? null : responsibleCustomRow"
                class="featureClassification"
                :rowKey="(row, index) => {return index;}"
                :row-selection="{
                type: 'radio',
                selectedRowKeys: responsibleSelectedRowKeys,
                onChange: responsibleRadioChange,
                getCheckboxProps:(record) => ({
                  props: {
                    disabled : distributeStatus == 1
                  }
                })
              }"
                bordered
                size="small"
                :scroll="{ y: 'calc(88vh - 400px)' }"
                :pagination="false">
            </a-table>
          </a-tab-pane>
          <a-tab-pane
              :tab="$t('functional-analysis.property-modal.date-and-status')"
              key="dateAndStatus">
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.status')">
                  <a-select
                      :disabled="distributeStatus==1"
                      @change="stateChange"
                      :defaultValue="dateAndStatus.state">
                    <a-select-option
                        v-for="(item, index) in stateSelect"
                        :key="index"
                        :value="item.value">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item required :label="$t('functional-analysis.property-modal.planning-date')">
                  <a-date-picker
                      class="width100"
                      :disabled="distributeStatus==1"
                      :allowClear="false"
                      :value="dateAndStatus.planDate"
                      valueFormat="YYYY-MM-DD"
                      @change="planDateChange"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.status-task')">
                  <a-input v-model="dateAndStatus.taskState" :disabled="true"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.start-date')">
                  <a-date-picker
                    class="width100"
                    :disabled="distributeStatus==1"
                    :allowClear="false"
                    :value="dateAndStatus.startDate"
                    valueFormat="YYYY-MM-DD"
                    @change="startDateChange"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.completion-date')">
                  <a-date-picker
                    class="width100"
                    :disabled="distributeStatus==1"
                    :allowClear="false"
                    :value="dateAndStatus.endDate"
                    valueFormat="YYYY-MM-DD"
                    @change="endDateChange"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('measure-track.take-evidence-based-measures')">
                  <a-textarea
                    :disabled="distributeStatus==1"
                    v-model="dateAndStatus.description"
                    :maxlength="500"
                    :rows="4"/>
                </a-form-item>
              </a-col>
            </a-row>
            <!-- <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.responsible-person')">
                  {{ dateAndStatus.userName }}
                </a-form-item>
              </a-col>
            </a-row> -->
          </a-tab-pane>
          <a-tab-pane
              :tab="$t('functional-analysis.property-modal.user-defined-characteristics')"
              key="userDefinedProperties">
            <a-table
                :data-source="userTableData"
                :columns="userTableColumns"
                :customRow="userCustomRow"
                :rowKey="(row, index) => {return index;}"
                :row-selection="{
                selectedRowKeys: userSelectedRowKeys,
                onChange: userCheckboxChange
               }"
                bordered
                size="small"
                :scroll="{ y: 'calc(88vh - 400px)' }"
                :pagination="false"/>
          </a-tab-pane>
          <a-tab-pane
              :tab="$t('functional-analysis.property-modal.note')"
              key="remarks">
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.note-group')">
                  <a-select
                      @change="nodeGroupChange"
                      v-model="currentNodeGroupKey"
                  >
                    <a-select-option
                        v-for="(item, index) in nodeGroups"
                        :key="index"
                        :value="item.annotationGroup"
                    >
                      {{ item.groupName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.note')">
              <span v-for="(item, index) in struNls">
                <a-textarea
                    v-if="defaultNls[0] === item.lkey"
                    :placeholder="$t('functional-analysis.property-modal.click-to-enter-note')"
                    allowClear
                    v-model="item.description"
                    :autoSize="{ minRows: 5 }"
                    :maxLength="500"
                />
              </span>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.attachment')">
                  <a-upload
                      name="file"
                      action=""
                      accept=".jpg,.txt,.png,.doc,.docx,.xls,.xlsx,.pdf,.pptx"
                      :fileList="fileList"
                      :customRequest="customRequest"
                      :remove="removeFile">
                    <a-button v-if="$api.isLook !== '1'">
                      <a-icon type="upload"/>
                      {{ $t('global-btn.select-file') }}
                    </a-button>
                  </a-upload>
                  <a-upload
                      name="file"
                      action=""
                      :disabled="distributeStatus==1"
                      accept=".jpg,.txt,.png,.doc,.docx,.xls,.xlsx,.pdf,.pptx"
                      :fileList="taskFileList"
                  >
                  </a-upload>
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>
          <a-tab-pane
              :tab="$t('functional-analysis.property-modal.about')"
              key="about">
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.create-time')">
                  {{ insertTime }}
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter='24'>
              <a-col :md="12" :sm="24">
                <a-form-item :label="$t('functional-analysis.property-modal.update-time')">
                  {{ updateTime }}
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </a-spin>
    </a-form>
    <div slot="footer"
         v-if="$api.isLook !== '1'"
         class="mt10 text-right">
      <a-button @click="closeModal">
        {{ $t('global-btn.cancel') }}
      </a-button>
      <a-button
          type="primary"
          class="ml10"
          @click="save()"
          :loading="saveLoading"
          v-preventReClick>
        {{ $t('global-btn.confirm') }}
      </a-button>
    </div>
  </div>
</template>
<script>

import {dateFormat} from "@/utils/date";
import {checkHotTableLength} from "@/utils/validate";
import $ from "jquery";
import moment from "moment";

/**
 * 渲染发生度表格
 * @param value
 * @param row
 * @param index
 * @returns {{children, attrs: {}}}
 */
const occurrenceRenderContent = (value, row, index) => {
  const obj = {
    children: value,
    attrs: {},
  };
  if (row.standardLevel === undefined) {
    obj.attrs.colSpan = 0;
  }
  return obj;
};

/**
 * 渲染负责人表格
 * @param value
 * @param row
 * @param index
 * @returns {{children, attrs: {}}}
 */
const responsibleRenderContent = (value, row, index) => {
  const obj = {
    children: value,
    attrs: {},
  };
  if (!row.userId) {
    obj.attrs.colSpan = 0;
  }
  return obj;
};

export default {
  name: "PropertyPreventionMeasure",
  components: {},
  props: {
    tabKey: {
      type: String,
      default: "",
    },
    checkedNode: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      /** tab默认选中 */
      tabName: this.tabKey || "name",
      /** 语言下拉数组 */
      currentNls: [],
      /** 语言名称数组 */
      struNls: [],
      /** 默认语言标识 */
      defaultNls: [],
      /** 名称 */
      name: "",
      /** 评估/发生度：输入值 */
      occurrenceInputVal: "",
      /** 评估/发生度：表格数据 */
      occurrenceTableData: [],
      /** 评估/发生度：表格表头 */
      occurrenceTableColumns: [
        {
          title: () => this.$t('functional-analysis.property-modal.level'),
          align: "center",
          width: 60,
          dataIndex: 'standardLevel',
          customRender: (text, row, index) => {
            if (row.standardLevel === undefined) text = row.attr1; /** 未设置 */
            if (row.standardLevel) return text;
            return {
              children: text,
              attrs: {
                colSpan: 6,
              },
            };
          },
          ellipsis: true,
        },
        {
          title: () => this.$t('functional-analysis.property-modal.failure-probability'),
          align: "center",
          dataIndex: 'attr1',
          customRender: occurrenceRenderContent,
          ellipsis: true,
        },
        {
          title: () => this.$t('functional-analysis.property-modal.occurrence-of-scoring-criteria'),
          align: "center",
          dataIndex: 'attr2',
          customRender: occurrenceRenderContent,
          ellipsis: true,
        },
        {
          title: () => this.$t('functional-analysis.property-modal.grading-criteria-process-experience'),
          align: "center",
          dataIndex: 'attr3',
          customRender: occurrenceRenderContent,
          ellipsis: true,
        },
        {
          title: () => this.$t('functional-analysis.property-modal.grading-standard-precautions'),
          align: "center",
          dataIndex: 'attr4',
          customRender: occurrenceRenderContent,
          ellipsis: true,
        },
        {
          title: () => this.$t('functional-analysis.property-modal.example-business-product-line'),
          align: "center",
          dataIndex: 'attr5',
          customRender: occurrenceRenderContent,
          ellipsis: true,
        },
      ],
      /** 评估/发生度：选中索引 */
      occurrenceSelectedRowKeys: [],
      /** 评估/发生度：选中数据 */
      occurrenceSelectedRow: {},
      /** 特性：应包含在FMEA表格里 */
      inFmeaFlag: "",
      /** 用户定义的特性：表格数据 */
      userTableData: [],
      /** 用户定义的特性：表格表头 */
      userTableColumns: [
        {
          title: () => this.$t('functional-analysis.property-modal.name'),
          align: "center",
          dataIndex: "memo",
          key: "memo",
          ellipsis: true,
        },
      ],
      /** 用户定义的特性：选中索引 */
      userSelectedRowKeys: [],
      /** 用户定义的特性：选中数据 */
      userSelectedRows: [],
      /** 负责人：表格数据 */
      responsibleTableData: [],
      /** 负责人：表格表头 */
      responsibleTableColumns: [
        {
          title: () => this.$t('functional-analysis.property-modal.name'),
          align: "center",
          dataIndex: 'userName',
          customRender: (text, row, index) => {
            if (row.userId) return text;
            return {
              children: text,
              attrs: {
                colSpan: 2,
              },
            };
          },
        },
        {
          title: () => this.$t('functional-analysis.property-modal.telephone'),
          align: "center",
          dataIndex: 'telephone',
          customRender: responsibleRenderContent,
        }
      ],
      /** 负责人：选中索引 */
      responsibleSelectedRowKeys: [],
      /** 负责人：选中数据 */
      responsibleSelectedRow: {},
      /** 测试：语言名称数组 */
      testStruNls: [],
      /** 测试 */
      test: {
        testName: "",
        testMethod: "",
        testStandard: "",
        testPlace: "",
        sampleRange: "",
      },
      /** 维修 */
      repair: {
        maintenanceCycle: undefined,
        maintenanceDateStart: undefined,
        maintenanceDateEnd: undefined,
        maintenanceMethod: undefined,
        acceptanceStandard: undefined,
        maintenanceFrequency: undefined,
      },
      // 维护频度字典(暂时写死 等待后期确认)
      maintenanceFrequencyDict: [
        {
          key: "1",
          value: this.$t('functional-analysis.property-modal.maintenance-once-a-day')
        },
        {
          key: "2",
          value: this.$t('functional-analysis.property-modal.maintenance-twice-a-day')
        },
        {
          key: "3",
          value: this.$t('functional-analysis.property-modal.maintenance-twice-a-week')
        },
        {
          key: "4",
          value: this.$t('functional-analysis.property-modal.maintenance-twice-a-month')
        }
      ],
      /** 分析 */
      analysis: {
        analysisName: '',
        analysisRequestNo: '',
        goal: '',
        analysisDescription: '',
        confidenceLevel: '',
        acceptanceCriteria: '',
        analysisList : [],
      },
      confidenceLevel: [
        {
          key: "1",
          value: "<10%"
        },
        {
          key: "2",
          value: "10%-30%"
        },
        {
          key: "3",
          "value": "30%-60%"
        },
        {
          key: "4",
          value: "60%-90%"
        },
        {
          key: "5",
          value: ">90%"
        },
      ],
      /** 日期与状态 */
      dateAndStatus: {
        state: "",
        taskState: "",
        planDate: "",
        startDate: "",
        endDate: "",
        userName: "",
        description: "",
      },
      /** 状态下拉 */
      stateSelect: [
        {value: "01", name: this.$t('global-dict.un-processed')},
        {value: "02", name: this.$t('global-dict.to-be-decided')},
        {value: "03", name: this.$t('global-dict.to-be-implemented')},
        {value: "04", name: this.$t('global-dict.abandon')},
        {value: "05", name: this.$t('global-dict.finish')},
      ],
      /** 备注分组 */
      nodeGroups: [],
      /** 默认备注分组Key */
      currentNodeGroupKey: undefined,
      /** 文件集合 */
      fileList: [],
      /** 文件集合 */
      taskFileList: [],
      /** 创建时间 */
      insertTime: "",
      /** 更新时间 */
      updateTime: "",
      /** 保存加载中... */
      saveLoading: false,
      /** 加载中状态 */
      loading: false,
      //分发状态
      distributeStatus:0,
    };
  },
  mounted() {
    this.list();
  },
  methods: {
    /**
     * 关闭模态框
     */
    closeModal() {
      this.$emit("closeModal");
    },
    /**
     * 刷新右侧结构树
     */
    initRightTree() {
      this.$emit("initRightTree");
    },
    /**
     * 名称改变时
     */
    nameChange(e) {
      this.struNls.forEach((item, index) => {
        if (item.lkey === this.defaultNls[0]) {
          item.name = e.target.value;
        }
      });
    },
    /**
     * 维护周期改变
     * @param date
     * @param dateString
     */
    closeDateChange(date, dateString) {
      this.repair.maintenanceCycle = date;
      this.repair.maintenanceDateStart = dateString[0] || undefined;
      this.repair.maintenanceDateEnd = dateString[1] || undefined;
    },
    /**
     * 维护频度改变事件
     * @param val
     */
    frequencyChange(val) {
      this.repair.maintenanceFrequency = val;
    },
    /**
     * 语言下拉选择时
     */
    currentNlsChange(val) {
      let struNls = this.struNls.filter((item) => {
        return item.lkey === val;
      })[0];
      this.defaultNls[0] = val;
      this.name = struNls.name;
    },
    /**
     * 备注分组下拉选择时
     */
    nodeGroupChange(val) {
      let _that = this;
      _that.currentNodeGroupKey = val;
      _that.$api.getNodeGroupSelect({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: _that.checkedNode.id,
        annotationGroup: _that.currentNodeGroupKey,
      }).then(res => {
        if (res.flag) {
          // 处理附件
          _that.handleFileList(res.data.rdfmAttachmentList || []);
          // 处理备注分组多语言
          let nodeGroupNls = res.data.rdfmAnnotationNlsList || [];
          const newStruNls = [..._that.struNls];
          (nodeGroupNls || []).forEach(nodeGroup => {
            (newStruNls || []).forEach(nls => {
              if (nls.lkey === nodeGroup.lkey) {
                nls.description = nodeGroup.lvalue;
              }
            })
          });
          _that.struNls = newStruNls;
        } else {
          _that.$message.error(res.message, 1);
        }
      });
    },
    /**
     * 测试语言下拉选择时
     */
    testCurrentNlsChange(val) {
      let struNls = this.testStruNls.filter((item) => {
        return item.lkey === val;
      })[0];
      this.test.testName = struNls.name;
    },
    /**
     * 措施分析语言下拉选择时
     */
    analysisNlsChange(val) {
      let struNls = this.struNls.filter((item) => {
        return item.lkey === val;
      })[0];
      this.analysis.analysisName = struNls.name;
      let analysis = this.analysis.analysisList.filter((item) => {
        return item.lkey === val;
      })[0];
      this.defaultNls[0] = val;
      if (analysis) {
        this.analysis.analysisDescription = analysis.analysisDescription;
        this.analysis.acceptanceCriteria = analysis.acceptanceCriteria;
        this.analysis.analysisRequestNo = analysis.analysisRequestNo;
        this.analysis.goal = analysis.goal;
        this.analysis.confidenceLevel = analysis.confidenceLevel;
      } else {
        this.analysis.acceptanceCriteria = "";
        this.analysis.analysisRequestNo = "";
        this.analysis.goal = "";
        this.analysis.analysisDescription = "";
        this.analysis.confidenceLevel = "";
      }
    },
    /**
     * 措施分析改变时
     */
    analysisChange(e, columnName) {
      this.analysis.analysisList.forEach((item, index) => {
        if (item.lkey === this.defaultNls[0]) {
          switch (columnName) {
            case 'analysisRequestNo' :
              item.analysisRequestNo = e.target.value;
              break;
            case 'acceptanceCriteria' :
              item.acceptanceCriteria = e.target.value;
              break;
            case 'goal' :
              item.goal = e.target.value;
              break;
            case 'analysisDescription' :
              item.analysisDescription = e.target.value;
              break;
            case 'confidenceLevel' :
              item.confidenceLevel = e;
              break;
          }
        }
      });
    },
    /**
     * 状态下拉选择时
     */
    stateChange(val) {
      this.dateAndStatus.state = val;
    },
    /**
     * 包含在FMEA表格选择时
     */
    inFmeaFlagChange(val) {
      if (val.target.checked) {
        this.inFmeaFlag = "1";
      } else {
        this.inFmeaFlag = "0";
      }
    },
    /**
     * 处理文件列表
     * @param files 文件
     */
    handleFileList(files) {
      this.fileList = []
      if (files.length === 0) return;
      for (let i = 0, len = files.length; i < len; i++) {
        this.fileList.push({
          data: {
            hiddenFileName: files[i].attachmentName,
            hiddenNewFileName: files[i].storageName,
            hiddenDir: files[i].attachmentPath,
            hiddenFileSize: files[i].attachmentSize,
          },
          uid: files[i].attachmentId,
          name: files[i].attachmentName,
          status: 'done',
          url: this.$api.requestUrl + '/DFMEA/funAnalysis/Rb0426141/downLoad?fmeaId=' + this.$store.getters.rfmeaId
              + '&attachmentId=' + files[i].attachmentId,
        });
      }
    },
    /**
     *      * 处理文件列表
     * @param files 文件
     */
    handleTaskFileList(files) {
      this.taskFileList = []
      if (files.length === 0) return;
      for (let i = 0, len = files.length; i < len; i++) {
        this.taskFileList.push({
          data: {
            hiddenFileName: files[i].attachmentName,
            hiddenNewFileName: files[i].storageName,
            hiddenDir: files[i].attachmentPath,
            hiddenFileSize: files[i].attachmentSize,
          },
          uid: files[i].attachmentId,
          name: files[i].attachmentName,
          status: 'done',
          url: this.$api.requestUrl + '/DFMEA/funAnalysis/Rb0426141/downLoad?fmeaId=' + this.$store.getters.rfmeaId
              + '&attachmentId=' + files[i].attachmentId,
        });
      }
    },
    /**
     * 列表
     */
    list() {
      let _that = this;
      _that.loading = true;
      _that.$api.getPreventiveMeasureProperties({
        fmeaId: _that.$store.getters.rfmeaId,
        lfmeaId: _that.$store.getters.fmeaId,
        struId: _that.checkedNode.id,
      }).then((res) => {
        if (res.flag) {
          this.distributeStatus = res.data.distributeStatus;
          /**************** 名称 ****************/
          if (!res.data.display_nls) res.data.display_nls = 1;
          _that.defaultNls[0] = res.data.display_nls;
          _that.currentNls = res.data.rdfmcurrentNls || [];
          // 语言Key升序
          _that.struNls = (res.data.rdfmStruNlss || []).sort((a, b) => {
            return a.lkey - b.lkey;
          });
          $.extend(true, _that.testStruNls, _that.struNls);
          let struNls = _that.struNls.filter((item) => {
            return res.data.display_nls === item.lkey;
          })[0];
          _that.name = struNls.name;
          /***************** 措施分析 ******************/
          _that.analysis.analysisName = struNls.name;
          _that.analysis.analysisList = (res.data.actionAnalysisList || []).sort((a, b) => {
            return a.lkey - b.lkey;
          });
          let analysisNls = _that.analysis.analysisList.filter((item) => {
            return res.data.display_nls === item.lkey;
          })[0];
          if (analysisNls) {
            _that.analysis.acceptanceCriteria = analysisNls.acceptanceCriteria;
            _that.analysis.analysisRequestNo = analysisNls.analysisRequestNo;
            _that.analysis.goal = analysisNls.goal;
            _that.analysis.analysisDescription = analysisNls.analysisDescription;
            _that.analysis.confidenceLevel = analysisNls.confidenceLevel;
          } else {
            _that.analysis.acceptanceCriteria = "";
            _that.analysis.analysisRequestNo = "";
            _that.analysis.goal = "";
            _that.analysis.analysisDescription = "";
            _that.analysis.confidenceLevel = "";
          }
          /**************** 评估/发生度 ****************/
          _that.occurrenceTableData = res.data.rfmStandardDetailOs || [];
          if (_that.occurrenceTableData && _that.occurrenceTableData.length > 0) {
            _that.occurrenceTableData.push({
              standardLevel: undefined,
              attr1: this.$t('functional-analysis.property-modal.not-set')
            });
            _that.occurrenceTableData.forEach((item, index) => {
              if (res.data.o === item.standardLevel) {
                _that.occurrenceSelectedRowKeys[0] = index;
                _that.occurrenceSelectedRow = item;
                _that.occurrenceInputVal = item.standardLevel;
              }
            });
            // 默认：未设置
            if (!res.data.o) {
              let ftSize = _that.occurrenceTableData.length;
              _that.occurrenceSelectedRowKeys[0] = ftSize - 1;
              _that.occurrenceSelectedRow = _that.occurrenceTableData[ftSize - 1];
              _that.occurrenceInputVal = _that.occurrenceSelectedRow.standardLevel;
            }
          }

          /**************** 维修 ****************/
          let repairData = res.data.mfmeaEquipmentInspection;
          if (repairData) {
            _that.repair.maintenanceMethod = repairData.maintenanceMethods;
            _that.repair.acceptanceStandard = repairData.acceptanceCriteria;
            _that.repair.maintenanceFrequency = repairData.maintenanceFrequency;
            _that.repair.maintenanceDateStart = repairData.maintenanceDateStart;
            _that.repair.maintenanceDateEnd = repairData.maintenanceDateEnd;
            let startDate = new Date(repairData.maintenanceDateStart);
            let endDate = new Date(repairData.maintenanceDateEnd);
            _that.repair.maintenanceCycle = [moment(startDate), moment(endDate)];
          }
          /**************** 特性 ****************/
          let action = res.data.rdfmAction;
          _that.inFmeaFlag = action.inFmeaFlag;
          /**************** 测试 ****************/
          _that.test.testName = struNls.name;
          _that.test.testMethod = action.testMethod;
          _that.test.testStandard = action.testStandard;
          _that.test.testPlace = action.testPlace;
          _that.test.sampleRange = action.sampleRange;
          /**************** 负责人 ****************/
          _that.responsibleTableData = res.data.rdfmPersonModels || [];
          if (_that.responsibleTableData && _that.responsibleTableData.length > 0) {
            _that.responsibleTableData.push({
              userId: "",
              userName: this.$t('functional-analysis.property-modal.not-set')
            });
            _that.responsibleTableData.forEach((item, index) => {
              if (res.data.rdfmAction.responsible === item.userId) {
                _that.responsibleSelectedRowKeys[0] = index;
                _that.responsibleSelectedRow = item;
              }
            });
            // 默认：未设置
            if (!res.data.rdfmAction.responsible) {
              let ftSize = _that.responsibleTableData.length;
              _that.responsibleSelectedRowKeys[0] = ftSize - 1;
              _that.responsibleSelectedRow = _that.responsibleTableData[ftSize - 1];
            }
          }
          /**************** 日期与状态 ****************/
          let fmeaTask = res.data.fmeaTask;
          _that.dateAndStatus.planDate = dateFormat(action.planDate);
          _that.dateAndStatus.state = action.state;
          _that.dateAndStatus.startDate = dateFormat(action.startDate);
          _that.dateAndStatus.endDate = dateFormat(action.endDate);
          _that.dateAndStatus.description = action.description;
          if (fmeaTask) {
            _that.dateAndStatus.taskState = action.trackTaskId
            && fmeaTask.status === 2
                ? this.$t('global-constant.measure-property.task-status.complete')
                : this.$t('global-constant.measure-property.task-status.in-working');
          }
          _that.dateAndStatus.userName = res.data.userName;
          /**************** 用户定义的特性 ****************/
          _that.userTableData = res.data.rdfmStruAttributeModels || [];
          _that.userTableData.forEach((item, index) => {
            if (item.checkFlag) {
              _that.userSelectedRowKeys.push(index);
              _that.userSelectedRows.push(item);
            }
          });
          /**************** 备注 ****************/
          _that.currentNodeGroupKey = res.data.currentGroupId;
          _that.nodeGroups = res.data.rdfmAnnotationGroupList || [];
          let nodeGroupNls = res.data.rdfmAnnotationNlsList || [];
          // 处理备注分组多语言
          (nodeGroupNls || []).forEach(nodeGroup => {
            (_that.struNls || []).forEach(nls => {
              if (nls.lkey === nodeGroup.lkey) {
                nls.description = nodeGroup.lvalue;
              }
            })
          });
          // 处理附件
          _that.handleFileList(res.data.rdfmAttachmentList || []);
          _that.handleTaskFileList(res.data.rdfmAttachmentTask || []);
          /**************** 关于 ****************/
          _that.insertTime = dateFormat(action?.insertTime);
          _that.updateTime = dateFormat(action?.updateTime);
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.loading = false;
      });
    },
    /**
     * 保存
     */
    save() {
      let _that = this;
      // 校验
      if (!_that.validatePropertyData()) return;

      /**************** 数据封装 Start ***********/
      let struNames = _that.struNls.map((item) => {
        return item.name;
      });
      let analysisRequestNos = _that.analysis.analysisList.map((item) => {
        return item.analysisRequestNo;
      });
      let acceptanceCriterias = _that.analysis.analysisList.map((item) => {
        return item.acceptanceCriteria;
      });
      let analysisDescriptions = _that.analysis.analysisList.map((item) => {
        return item.analysisDescription;
      });
      let confidenceLevels = _that.analysis.analysisList.map((item) => {
        return item.confidenceLevel;
      });
      let goals = _that.analysis.analysisList.map((item) => {
        return item.goal;
      });
      let descriptions = _that.struNls.map((item) => {
        return item.description || '';
      });
      let userDefineIds = _that.userSelectedRows.map((item) => {
        return item.userDefineId;
      });
      let responsible = _that.responsibleSelectedRow ? _that.responsibleSelectedRow.userId : '';
      let hiddenFileName = [];
      let hiddenNewFileName = [];
      let hiddenDir = [];
      let hiddenFileSize = [];
      let files = _that.fileList;
      for (let i = 0, len = files.length; i < len; i++) {
        let file = files[i].data;
        hiddenFileName.push(file.hiddenFileName);
        hiddenNewFileName.push(file.hiddenNewFileName);
        hiddenDir.push(file.hiddenDir);
        hiddenFileSize.push(file.hiddenFileSize);
      }
      /**************** 数据封装 End ***********/

      _that.saveLoading = true; // 开启：加载中...
      _that.$api.savePreventiveMeasureProperties({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: _that.checkedNode.id,
        struNames: struNames, /** 名称 */
        occurrence: _that.occurrenceInputVal, /** 评估/发生度 */
        testMethod: _that.test.testMethod, /** 测试方法 */
        inFmeaFlag: _that.inFmeaFlag, /** 应包含在FMEA表格里 */
        testStandard: _that.test.testStandard, /** 接受标准 */
        testPlace: _that.test.testPlace, /** 测试地点 */
        sampleRange: _that.test.sampleRange, /** 抽样覆盖范围 */
        responsible: responsible, /** 负责人 */
        state: _that.dateAndStatus.state, /** 状态 */
        planDate: Date.parse(_that.dateAndStatus.planDate), /** 规划日期 */
        startDate: Date.parse(_that.dateAndStatus.startDate), /** 开始日期 */
        endDate: Date.parse(_that.dateAndStatus.endDate), /** 结束日期 */
        description: _that.dateAndStatus.description, /** 描述 */
        userDefineIds: userDefineIds, /** 用户定义的特性 */
        descriptions: descriptions, /** 备注 */
        lkey: _that.defaultNls[0], /** 备注分组语言Key */
        annotationGroup: _that.currentNodeGroupKey, /** 备注分组Key */
        hiddenFileName: hiddenFileName, /** 隐藏的附件名称 */
        hiddenNewFileName: hiddenNewFileName, /** 隐藏的新生成附件名称 */
        hiddenDir: hiddenDir, /** 隐藏的新生成附件名称 */
        hiddenFileSize: hiddenFileSize, /** 隐藏的新生成附件大小 */
        analysisRequestNos: analysisRequestNos, /** 分析请求编号 */
        goals: goals, /** 目的 */
        analysisDescriptions: analysisDescriptions, /** 分析描述 */
        confidenceLevels: confidenceLevels, /** 分析模型的置信度 */
        acceptanceCriterias: acceptanceCriterias, /** 验收标准 */
        maintenanceDateStart: _that.repair.maintenanceDateStart, /** 维护周期开始日期 */
        maintenanceDateEnd: _that.repair.maintenanceDateEnd, /** 维护周期结束日期 */
        maintenanceMethod: _that.repair.maintenanceMethod, /** 维护方法 */
        acceptanceStandard: _that.repair.acceptanceStandard, /** 接收准则 */
        maintenanceFrequency: _that.repair.maintenanceFrequency, /** 维护频度 */
      }).then((res) => {
        if (res.flag) {
          // 添加成功，关闭弹窗，刷新结构树
          _that.$message.success(res.message, 1);
          _that.closeModal();
          _that.initRightTree();
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.saveLoading = false; // 关闭：加载中...
      })
    },
    /**
     * 校验：属性数据
     */
    validatePropertyData() {
      let flag = true;
      this.struNls.some((item, idx) => {
        let nlsKey = this.$t('global-dict.select-nls.' + item.lkey);
        if (!item.name) {
          this.$message.warning(this.$t('global-message.warn.name-cannot-be-empty', [nlsKey]));
          flag = false;
          return true;
        }
        if (checkHotTableLength(item.name, 1000)) {
          this.$message.warning(this.$t('global-message.warn.name-cannot-be-empty', [nlsKey]));
          flag = false;
          return true;
        }
        if (checkHotTableLength(item.description, 500)) {
          this.$message.warning(this.$t('global-message.warn.name-cannot-be-empty', [nlsKey]));
          flag = false;
          return true;
        }
      });
      if (!this.dateAndStatus.planDate) {
        this.$message.warning(this.$t('global-message.warn.planning-date-cannot-be-empty'));
        flag = false;
      }
      return flag;
    },
    /**
     * 发生度：数字选择器改变时
     */
    occurrenceInputValChange(val) {
      this.occurrenceTableData.forEach((item, index) => {
        if (item.standardLevel === val) {
          this.occurrenceSelectedRowKeys = [index];
          this.occurrenceSelectedRow = item;
          this.occurrenceInputVal = item.standardLevel;
        }
      });
    },
    /**
     * 发生度：单选框改变事件
     */
    occurrenceRadioChange(rowKeys, row) {
      this.occurrenceSelectedRowKeys = rowKeys;
      this.occurrenceSelectedRow = row[0];
      this.occurrenceInputVal = row[0].standardLevel;
    },
    /**
     * 发生度：行点击事件
     */
    occurrenceCustomRow(record, index) {
      let _that = this;
      return {
        on: {
          // 鼠标单击行
          click: () => {
            _that.occurrenceSelectedRowKeys = [index];
            _that.occurrenceSelectedRow = record;
            _that.occurrenceInputVal = record.standardLevel;
          }
        }
      };
    },
    /**
     * 用户定义的特性：复选框改变事件
     */
    userCheckboxChange(rowKeys, row) {
      this.userSelectedRows = row;
      this.userSelectedRowKeys = rowKeys;
    },
    /**
     * 用户定义的特性：行点击事件
     */
    userCustomRow(record, index) {
      let _that = this;
      return {
        on: {
          // 鼠标单击行
          click: () => {
            if (_that.userSelectedRowKeys.indexOf(index) !== -1) {
              _that.userSelectedRows.splice(_that.userSelectedRowKeys.indexOf(index), 1);
              _that.userSelectedRowKeys.splice(_that.userSelectedRowKeys.indexOf(index), 1);
            } else {
              _that.userSelectedRowKeys.push(index)
              _that.userSelectedRows.push(record);
            }
          }
        }
      };
    },
    /**
     * 负责人：单选框改变事件
     */
    responsibleRadioChange(rowKeys, row) {
      this.responsibleSelectedRowKeys = rowKeys;
      this.responsibleSelectedRow = row[0];
    },
    /**
     * 负责人：行点击事件
     */
    responsibleCustomRow(record, index) {
      let _that = this;
      return {
        on: {
          // 鼠标单击行
          click: () => {
            _that.responsibleSelectedRowKeys = [index];
            _that.responsibleSelectedRow = record;
          }
        }
      };
    },
    /**
     * 规划日期改变时
     */
    planDateChange(val) {
      this.dateAndStatus.planDate = val;
    },
    /**
     * 开始日期改变时
     */
     startDateChange(val) {
      this.dateAndStatus.startDate = val;
    },
    /**
     * 结束日期改变时
     */
     endDateChange(val) {
      this.dateAndStatus.endDate = val;
    },
    /**
     * 通过覆盖默认的上传行为，可以自定义自己的上传实现
     * @param obj 回调对象
     */
    customRequest(obj) {
      let _that = this;
      if (obj.file.size > 52428800) {
        _that.$message.warning(this.$t('global-message.warn.uploaded-files-cannot-exceed'));
        return;
      }
      _that.loading = true;
      let fd = new FormData();
      fd.append("file", obj.file);
      fd.append("fileType", "10");
      _that.$api.uploadFile(fd).then((res) => {
        if (res.flag) {
          _that.$message.success(res.message, 1);
          obj.file.data = {
            hiddenFileName: res.data.fileName,
            hiddenNewFileName: res.data.newFileName,
            hiddenDir: res.data.filePath,
            hiddenFileSize: res.data.fileSize,
          };
          _that.fileList.push(obj.file);
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.loading = false;
      });
    },
    /**
     * 删除文件
     * @param file 文件
     */
    removeFile(file) {
      let files = this.fileList;
      for (let i = files.length - 1; i >= 0; i--) {
        if (file.uid === files[i].uid) files.splice(i, 1);
      }
    },
  }
};
</script>
<style lang="less" scoped>

/** 表格头部自动换行 */
/deep/ .ant-table-thead {
  .ant-table-row-cell-ellipsis .ant-table-column-title {
    white-space: normal;
  }
}

/deep/ .ant-col-3 {
  width: 10% !important;
}

/deep/ .ant-table-tbody {
  .ant-table-row-cell-ellipsis:nth-of-type(2) {
    text-align: left !important;
  }

  .ant-table-row-cell-ellipsis:nth-of-type(3) {
    text-align: left !important;
  }

  .ant-table-row-cell-ellipsis:nth-of-type(4) {
    text-align: left !important;
  }

  .ant-table-row-cell-ellipsis:nth-of-type(5) {
    text-align: left !important;
  }

  .ant-table-row-cell-ellipsis:nth-of-type(6) {
    text-align: left !important;
  }
}

// 评估/级别居中
/deep/ .evaluate {
  .ant-table-tbody {
    .ant-table-row-cell-ellipsis:nth-of-type(2) {
      text-align: center !important;
    }
  }
}

/*/deep/ .ant-table-fixed-header > .ant-table-content > .ant-table-scroll > .ant-table-body {
  overflow-y: auto !important;
}*/

/deep/ a {
  color: #1890FF;
}
/deep/ .ant-table-fixed-header .ant-table-scroll .ant-table-header {
  overflow: hidden!important;
  margin-bottom: 0!important;
  padding-right: 8px;
  background: rgb(250, 250, 250);
}
</style>
