<template>
  <app-dialog v-model="visible" :loading="resultLoading" append-to-body class="detail-dialog" hide-footer
              title="结果配置" width="60%"
  >
    <div class="page-view flex-row-sb">
      <app-sync-tree
        ref="appAsyncTree"
        :actions="treeActions"
        :default-data="{ customConfigField: 'custom config field' }"
        :default-expanded-keys="defaultExpandedKeys"
        :expand-all="false"
        :fields="treeFields"
        :props="treeProps"
        :request-method="getTreeNodes"
        title="维度值列表"
        @select="onTreeNodeClick"
      />

      <div class="page-view flex-1 ml-15 h-100">
        <div class="pa-11 bg-white h-100 flex-col border-radius-5">
          <el-form ref="addFormRef" :inline="true" :model="addFormData" :rules="addFormRules" size="mini">
            <el-table :data="addFormData.productList" border tooltip-effect="light">
              <el-table-column
                label="序号"
                type="index"
                width="50"
              />
              <el-table-column align="center" label="特征名称" prop="indexName" width="200">
                <template v-slot="{ row,$index }">
                  <el-form-item :prop="`productList.${$index}.indexName`" :rules="addFormRules.indexName" size="mini"
                                style="width: 100%"
                  >
                    <el-input v-model="row.indexName" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入"
                              type="textarea"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="特征描述" prop="reasonContent">
                <template v-slot="{ row,$index }">
                  <el-form-item :prop="`productList.${$index}.reasonContent`" :rules="addFormRules.reasonContent"
                                style="width: 100%"
                  >
                    <el-input v-model="row.reasonContent" :autosize="{ minRows: 2, maxRows: 4 }"
                              placeholder="请输入特征描述"
                              type="textarea"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="180">
                <template v-slot="{ row,$index }">
                  <el-button icon="el-icon-edit" size="mini" type="text"
                             @click="handleUpdateYes(row,$index)"
                  >增加
                  </el-button>
                  <el-button icon="el-icon-delete" size="mini" style="color:red" type="text"
                             @click="handleDeleteProduct(row,$index)"
                  >删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </div>
    </div>
    <div ref="dialogFooter" slot="footer" class="gz-dialog-footer text-r" style="margin-top: 10px">
      <el-button :loading="resultLoading" class="confirm_btn"
                 type="primary" @click="handleSubmitAdd"
      >确
      定
      </el-button>
      <el-button class="cancel_btn" @click="onCancel">取 消</el-button>
    </div>
  </app-dialog>
</template>

<script>
import dialogMixin from '@/mixins/dialog.js';
import tableMixin from '@/mixins/table.js';
import { getDictionaryByCode } from '@/utils/dictionary';
import API from '@/api/business/arithmeticInfo';

export default {
  name: 'ResultDialog',
  mixins: [dialogMixin, tableMixin],
  props: {
    data: {
      type: Object,
      default: () => {
      },
    },
    indexType: {
      type: String,
      default: '1',
    },
  },
  data() {
    return {
      resultLoading: false,
      treeProps: {
        value: 'id',
        label: 'name',
      },
      defaultExpandedKeys: ['0'],
      treeFields: [],
      curNode: {}, // 当前选择节点
      form: {},
      addFormData: {
        productList: [],
      },
      addFormRules: {
        indexName: [{
          required: true,
          message: '请输入特征名称',
          trigger: 'blur',
        }],
        reasonContent: [{
          required: true,
          message: '请输入特征描述',
          trigger: 'blur',
        },
        ],
      },
      searchFrom: {
        'querys': [
          {
            'operation': 'EQUAL',
            'property': 'reasonKey',
            'relation': 'AND',
            'value': '',
          },
          {
            'operation': 'EQUAL',
            'property': 'indexId',
            'relation': 'AND',
            'value': this.data.id,
          },
        ],
        'pageBean': {
          'page': 1,
          'pageSize': 100,
        },
        'sorter': [],
      },
    };
  },
  methods: {
    getDictionaryByCode,
    // 新增
    handleUpdateYes(row) {
      this.addFormData.productList.push({
        indexName: '',
        reasonContent: '',
        indexId: this.data.id,
        indexType: this.indexType,
        reasonKey: this.curNode.id,
        reasonValue: this.curNode.text,
      });
    },
    // 删除
    async handleDeleteProduct(row, index) {
      const { state } = await API.deleteResultItem(row.id);
      if (state) {
        await this.getDefaultChange();
        this.$message.success('删除成功！');
      } else {
        this.$message.warning('删除失败！');
      }
      // this.addFormData.productList.splice(index, 1);
    },
    // 提交
    handleSubmitAdd() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          const { state } = await API.saveAlgorithmResultItemBatch(this.addFormData.productList);
          if (state) {
            this.visible = false;
            this.$message.success('保存成功');
          }
        } else {
          return false;
        }
      });
    },
    async getTreeNodes() {
      let params = [];
      if (this.data.fieldValueType === 2) {
        params = getDictionaryByCode(this.data.dimensionId);
      } else if (this.data.fieldValueType === 3) {
        params = await API.getByDicKey(this.data.dimensionId);
      }
      return { data: params || [] };
    },
    treeActions(data) {
      return [];
    },
    onTreeNodeClick(node) {
      if (node.id === this.curNode?.id) return;
      this.deptName = node.label;
      this.curNode = { ...node };
      this.searchFrom.querys[0].value = node.id;
      this.getDefaultChange();
    },
    async getDefaultChange() {
      const data = await API.resultItemChange(this.searchFrom);
      if (data.total === 0) {
        this.addFormData.productList = [];
        this.addFormData.productList.push({
          indexName: '',
          reasonContent: '',
          indexType: this.indexType,
          indexId: this.data.id,
          reasonKey: this.curNode.id,
          reasonValue: this.curNode.text,
        });
      } else {
        this.addFormData.productList = data.rows;
      }
    },
    onCancel() {
      this.addFormData.productList = [];
      this.visible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .app-dialog-content {
  padding: 0 !important;
}

::v-deep .el-table__cell:first-child .cell {
  text-align: center;
}

::v-deep .el-table__body-wrapper {
  height: calc(100vh - 10vh - 320PX);
  overflow-y: auto;
}

::v-deep .el-form-item__content {
  width: 100%;
}

.titleFlex {
  display: flex;
  margin: 10px 0;

  .titleStyle {
    font-size: 16px;
    font-weight: bold;
    text-align: center;
  }
}

.contentStyle {
  padding-bottom: 30px;
}

.typeStyle {
  font-size: 15px;
  font-weight: bold;
  text-align: center;
}

.padingName {
  padding: 0px 30px;
  box-sizing: border-box;
}
</style>
