<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.equipment-name')">
                  <a-input
                      v-model="name"
                      :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.equipment-number')">
                  <a-input v-model="equipmentCode" :maxLength="60"/>
                </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.equipment-classification')">
                  <a-input v-model="classify" :maxLength="32" :placeholder="$t('global-constant.please-enter') + $t('functional-analysis.property-modal.equipment-classification')" />
                </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.interface')"
              key="interface">
            <a-table
                :data-source="interfaceTableData"
                :columns="interfaceTableColumns"
                :rowKey="(row, index) => {return index;}"
                :row-selection="{
                columnTitle:' ',
                selectedRowKeys: interfaceSelectedRowKeys,
                onChange: interfaceCheckboxChange,
                getCheckboxProps: getCheckboxProps
              }"
                bordered
                size="small"
                :scroll="{ y: 'calc(88vh - 400px)' }"
                :pagination="false">
              <template slot="titleScore">{{ struName }}</template>
              <template slot="linkDirect" slot-scope="text, row">
              <span>
                {{
                  row.linkDirect === '1'
                      ? $t('global-constant.structure-property.unidirectional')
                      : $t('global-constant.structure-property.two-way')
                }}
              </span>
              </template>
              <template slot="status" slot-scope="text, row">
              <span>
                {{
                  row.status === '0'
                      ? $t('global-constant.structure-property.analyzed')
                      : $t('global-constant.structure-property.not-analyzed')
                }}
              </span>
              </template>
            </a-table>
          </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" :key="index">
                <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-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";

export default {
  name: "PropertyStructure",
  components: {},
  props: {
    tabKey: {
      type: String,
      default: "",
    },
    checkedNode: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      /** tab默认选中 */
      tabName: this.tabKey || "name",
      /** 语言下拉数组 */
      currentNls: [],
      /** 语言名称数组 */
      struNls: [],
      /** 默认语言标识 */
      defaultNls: [],
      /** 设备名称 */
      name: "",
      /** 设备编号 */
      equipmentCode: "",
      /** 设备分类 */
      classify: "",
      /** 用户定义特性：表格数据 */
      userTableData: [],
      /** 用户定义特性：表格表头 */
      userTableColumns: [
        {
          title: () => this.$t('functional-analysis.property-modal.name'),
          align: "center",
          dataIndex: "memo",
          key: "memo",
          ellipsis: true,
        },
      ],
      /** 用户定义特性：选中索引 */
      userSelectedRowKeys: [],
      /** 用户定义特性：选中数据 */
      userSelectedRows: [],
      /** 当前结构名称 */
      struName: "",
      /** 接口：表格数据 */
      interfaceTableData: [],
      /** 接口：表格表头 */
      interfaceTableColumns: [
        {
          title: () => this.$t('functional-analysis.property-modal.name'),
          align: "center",
          children: [
            {
              title: () => this.$t('functional-analysis.property-modal.connection-object'),
              align: "center",
              dataIndex: 'toStruName',
              ellipsis: true,
            },
          ]
        },
        {
          align: "left",
          scopedSlots: {
            title: 'titleScore'
          },
          children: [
            {
              title: () => this.$t('functional-analysis.property-modal.connection-direction'),
              align: "center",
              dataIndex: 'directionName',
              ellipsis: true,
            },
            {
              title: () => this.$t('functional-analysis.property-modal.connection-method'),
              align: "center",
              dataIndex: 'linkName',
              ellipsis: true,
            },
            {
              title: () => this.$t('functional-analysis.property-modal.connection-type'),
              align: "center",
              dataIndex: 'linkDirect',
              scopedSlots: {
                customRender: 'linkDirect' /** 1：单向，2：双向 */
              },
              ellipsis: true,
            },
            {
              title: () => this.$t('functional-analysis.property-modal.status'),
              align: "center",
              width: 80,
              dataIndex: 'status',
              scopedSlots: {
                customRender: 'status' /** 1：未分析，2：已分析 */
              },
              ellipsis: true,
            },
            {
              title: () => this.$t('functional-analysis.property-modal.interface-function'),
              align: "center",
              dataIndex: 'interfaceFunction',
              ellipsis: true,
            },
          ],
        },
      ],
      /** 接口：选中索引 */
      interfaceSelectedRowKeys: [],
      /** 接口：选中数据 */
      interfaceSelectedRows: [],
      /** 接口：默认选中 */
      defaultCheckedStruIds: [],
      /** 备注分组 */
      nodeGroups: [],
      /** 默认备注分组Key */
      currentNodeGroupKey: undefined,
      /** 文件集合 */
      fileList: [],
      /** 创建时间 */
      insertTime: "",
      /** 更新时间 */
      updateTime: "",
      /** 保存加载中... */
      saveLoading: false,
      /** 加载中状态 */
      loading: false,
    };
  },
  mounted() {
    this.list();
  },
  methods: {
    /**
     * 关闭模态框
     */
    closeModal() {
      this.$emit("closeModal");
    },
    /**
     * 刷新左侧结构树
     */
    initLeftTree() {
      this.$emit("initLeftTree");
    },
    /**
     * 刷新右侧结构树
     */
    initRightTree() {
      this.$emit("initRightTree");
    },

    initNodesData() {
      this.$emit('initNodesData');
    },
    /**
     * 名称改变时
     */
    nameChange(e) {
      this.struNls.forEach((item, index) => {
        if (item.lkey === this.defaultNls[0]) {
          item.name = e.target.value;
        }
      });
    },
    /**
     * 语言下拉选择时
     */
    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.mfmeaAttachmentList || []);
          // 处理备注分组多语言
          let nodeGroupNls = res.data.mfmeaAnnotationNlsList || [];
          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);
        }
      });
    },
    /**
     * 处理文件列表
     * @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/mfmea/funAnalysis/Rb0426341/downLoad?fmeaId=' + this.$store.getters.rfmeaId
              + '&attachmentId=' + files[i].attachmentId,
        });
      }
    },
    /**
     * 列表
     */
    list() {
      let _that = this;
      _that.loading = true;
      _that.$api.getStructureProperties({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: _that.checkedNode.id,
      }).then((res) => {
        if (res.flag) {
          /**************** 名称 ****************/
          if (!res.data.display_nls) res.data.display_nls = 1;
          _that.defaultNls[0] = res.data.display_nls;
          _that.currentNls = res.data.mfmeacurrentNls || [];
          // 语言Key升序
          _that.struNls = (res.data.mfmeaStruNlss || []).sort((a, b) => {
            return a.lkey - b.lkey;
          });
          let struNls = _that.struNls.filter((item) => {
            return res.data.display_nls === item.lkey;
          })[0];
          _that.name = struNls.name;
          _that.equipmentCode = res.data.mfmeaStruElement.equipmentCode;
          // 设备分类
          _that.classify = res.data.mfmeaStruElement.equipmentType;
          /**************** 用户定义的特性 ****************/
          _that.userTableData = res.data.mfmeaStruAttributeModels;
          _that.userTableData.forEach((item, index) => {
            if (item.checkFlag) {
              _that.userSelectedRowKeys.push(index);
              _that.userSelectedRows.push(item);
            }
          });
          /**************** 接口 ****************/
          _that.struName = res.data.struName;
          _that.interfaceTableData = res.data.interfaceInfos || [];
          _that.interfaceTableData.forEach((item, index) => {
            if (item.status === 0) {
              _that.defaultCheckedStruIds.push(item.struId);
              _that.interfaceSelectedRowKeys.push(index);
              _that.interfaceSelectedRows.push(item);
            }
          });
          /**************** 备注 ****************/
          _that.currentNodeGroupKey = res.data.currentGroupId;
          _that.nodeGroups = res.data.mfmeaAnnotationGroupList || [];
          let nodeGroupNls = res.data.mfmeaAnnotationNlsList || [];
          // 处理备注分组多语言
          (nodeGroupNls || []).forEach(nodeGroup => {
            (_that.struNls || []).forEach(nls => {
              if (nls.lkey === nodeGroup.lkey) {
                nls.description = nodeGroup.lvalue;
              }
            })
          });
          // 处理附件
          _that.handleFileList(res.data.mfmeaAttachmentList || []);
          /**************** 关于 ****************/
          _that.insertTime = dateFormat(res.data.mfmeaStruElement?.insertTime);
          _that.updateTime = dateFormat(res.data.mfmeaStruElement?.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 descriptions = _that.struNls.map((item) => {
        return item.description || '';
      });
      let userDefineIds = _that.userSelectedRows.map((item) => {
        return item.userDefineId;
      });
      let chartStruIds = _that.interfaceSelectedRows.map((item) => {
        return item.struId;
      });
      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.saveStructureProperties({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: _that.checkedNode.id,
        struNames: struNames, /** 设备名称 */
        equipmentCode: _that.equipmentCode, /** 设备编号 */
        equipmentType: _that.classify, /** 设备分类 */
        userDefineIds: userDefineIds, /** 用户定义的特性 */
        descriptions: descriptions, /** 备注 */
        lkey: _that.defaultNls[0], /** 备注分组语言Key */
        annotationGroup: _that.currentNodeGroupKey, /** 备注分组Key */
        hiddenFileName: hiddenFileName, /** 隐藏的附件名称 */
        hiddenNewFileName: hiddenNewFileName, /** 隐藏的新生成附件名称 */
        hiddenDir: hiddenDir, /** 隐藏的新生成附件名称 */
        hiddenFileSize: hiddenFileSize, /** 隐藏的新生成附件大小 */
        chartStruIds: chartStruIds, /** 边界图连线struid */
      }).then((res) => {
        if (res.flag) {
          // 添加成功，关闭弹窗，刷新结构树
          _that.$message.success(res.message, 1);
          _that.closeModal();
          _that.initLeftTree();
          _that.initRightTree();
          _that.initNodesData();
        } 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;
        }
      });
      return flag;
    },
    /**
     * 复选框改变事件
     */
    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);
            }
          }
        }
      };
    },
    /**
     * 复选框改变事件
     */
    interfaceCheckboxChange(rowKeys, row) {
      this.interfaceSelectedRows = row;
      this.interfaceSelectedRowKeys = rowKeys;
      this.interfaceTableData.forEach((item, index) => {
        if (rowKeys.indexOf(index) !== -1)
          item.status = 0;
        else item.status = 1;
      });
    },
    /**
     * 默认属性配置
     */
    getCheckboxProps: record => ({
      props: {
        defaultChecked: true,
        disabled: true
        // disabled: record.status === 0
      },
    }),
    /**
     * 行点击事件
     */
    interfaceCustomRow(record, index) {
      let _that = this;
      return {
        on: {
          // 鼠标单击行
          click: () => {
            if (_that.defaultCheckedStruIds.indexOf(record.struId) !== -1) return;
            let checkedIndex = index;
            this.interfaceTableData.forEach((item, index) => {
              if (checkedIndex === index) item.status = item.status === 0 ? 1 : 0;
            });
            if (_that.interfaceSelectedRowKeys.indexOf(index) !== -1) {
              _that.interfaceSelectedRows.splice(_that.interfaceSelectedRowKeys.indexOf(index), 1);
              _that.interfaceSelectedRowKeys.splice(_that.interfaceSelectedRowKeys.indexOf(index), 1);
            } else {
              _that.interfaceSelectedRowKeys.push(index)
              _that.interfaceSelectedRows.push(record);
            }
          }
        }
      };
    },
    /**
     * 通过覆盖默认的上传行为，可以自定义自己的上传实现
     * @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-tbody {
  .ant-table-row-cell-ellipsis:nth-of-type(2) {
    text-align: left !important;
  }
}

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

/deep/ a {
  color: #1890FF;
}

</style>
