<template>
  <app-dialog v-model="visible" :loading="loading" :title="title" append-to-body class="detail-dialog"
    @cancel="onCancel" @confirm="onConfirm" width="66%">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row type="flex" justify="start" :gutter="20">
        <app-filter-item :span="12" label="字典项名称" prop="name">
          <el-input v-model="form.name" clearable placeholder="请输入" />
        </app-filter-item>
        <app-filter-item :span="12" label="字典项编码" prop="code">
          <el-input v-model="form.code" v-pinyin="form.name" clearable placeholder="请输入" />
        </app-filter-item>
      </el-row>
      <el-row type="flex" justify="start">
        <app-filter-item :span="24" label="字典项备注" prop="memo">
          <el-input v-model="form.memo" clearable placeholder="请输入" />
        </app-filter-item>
      </el-row>
      <el-row>
        <el-col :span="20">
          <app-filter-item :span="24" label="解析文本">
            <el-input type="textarea" :rows='4' style="width:100%" v-model="excleText" placeholder="请将excel数据复制至此">
            </el-input>
          </app-filter-item>
        </el-col>
        <el-col :span="3" :offset="1">
          <el-button @click="analysisText" type="primary" icon="el-icon-magic-stick">解析</el-button>
          <el-tooltip class="item ml-20" content="请复制excel数据到文本框中解析为字典表！" placement="bottom">
            <i class="el-icon-info tips-text" style="color: #e6a23c"></i>
          </el-tooltip>
        </el-col>
      </el-row>
      <el-row class="mb-20">
        <el-button type="primary" @click="handleAdd">添加
        </el-button>
        <el-button type="danger" :disbled="multipleSelection.length <= 0" plain @click="handleDictItemDel">删除
        </el-button>
        <el-button type="success" :disbled="multipleSelection.length <= 0" plain @click="handleDictItemFlag(1)">启用
        </el-button>
        <el-button type="danger" :disbled="multipleSelection.length <= 0" plain @click="handleDictItemFlag(0)">禁用
        </el-button>
        <el-button type="primary" plain @click="handleIndex">保存排序号
        </el-button>
      </el-row>
      <el-table ref="nodeTable" class="edit-dict-table" border :height="tableHeight" :data="form.details"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" header-align="center" align="center" width="45">
        </el-table-column>
        <el-table-column label="成员名称" header-align="center">
          <template slot="header">
            <span>
              <span class="fs-14" style="color: #f56c6c">*</span>
              成员名称
              <el-tooltip class="item" content="成员名称不能重复" placement="bottom">
                <i class="el-icon-info fs-14" style="color: #e6a23c"></i>
              </el-tooltip>
            </span>
          </template>
          <template slot-scope="scope">
            <app-filter-item :prop="`details.${scope.$index}.name`" :rules="formRules.name" :span="24">
              <el-input v-model="scope.row.name" placeholder="请输入成员名称" />
            </app-filter-item>
          </template>
        </el-table-column>
        <el-table-column label="成员值" header-align="center">
          <template slot="header">
            <span>
              <span class="fs-14" style="color: #f56c6c">*</span>
              成员值
              <el-tooltip class="item" content="成员值不能重复" placement="bottom">
                <i class="el-icon-info fs-14" style="color: #e6a23c"></i>
              </el-tooltip>
            </span>
          </template>
          <template slot-scope="scope">
            <app-filter-item :prop="`details.${scope.$index}.value`" :rules="formRules.value" :span="24">
              <el-input v-model="scope.row.value" placeholder="请输入成员值" />
            </app-filter-item>
          </template>
        </el-table-column>
        <el-table-column label="排序号" align="center" width="120px">
          <template slot-scope="scope">
            <ht-input width="100%" v-model="scope.row.sn" type="number" :min="1" :validate="{ required: true }"
              @change="changeSN(scope.row, 'sn')"></ht-input>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="120px">
          <template slot-scope="scope">
            <el-tag :type="scope.row.flag == -1
              ? 'info'
              : scope.row.flag == 1
                ? 'success'
                : 'danger'
              ">{{
                scope.row.flag == -1
                  ? '草稿'
                  : scope.row.flag == 1
                    ? '启用'
                    : '禁用'
              }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </app-dialog>
</template>

<script>
import utils from '@/utils.js';
import dialogMixin from '@/mixins/dialog.js';
import API from '@/api/business/dict.js';
export default {
  name: 'dictDialog',
  mixins: [dialogMixin],
  props: {
    selectedRows: {
      type: Array,
      default: () => [],
    },
    parent: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    var checValue = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('成员值不能为空'));
      } else {
        if (this.form.details.filter((item) => item.value === value).length > 1) {
          callback(new Error('成员值不能重复!'));
        } else {
          callback();
        }
      }
    };
    var checName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('成员名称不能为空'));
      } else {
        if (this.form.details.filter((item) => item.name === value).length > 1) {
          callback(new Error('成员名称不能重复!'));
        } else {
          callback();
        }
      }
    };
    return {
      form: {
        name: '',
        code: '',
        treeId: '',
        details: [],
      },
      rules: {
        name: [{ required: true, message: '字典项名称不能为空' }],
        code: [{ required: true, message: '字典项编码不能为空' }],
      },
      excleText: '',
      tableHeight: '300px',
      loading: false,
      snChange: null,
      multipleSelection: [],
      formRules: {
        name: [
          {
            required: true,
            message: '成员名称不能为空',
            trigger: 'blur',
          },
          { validator: checName, trigger: 'blur' },
        ],
        value: [
          {
            required: true,
            message: '成员值不能为空',
            trigger: 'blur',
          },
          { validator: checValue, trigger: 'blur' },
        ],
      },
    };
  },
  mounted() { },
  methods: {
    /**
     * @description: dialog每次显示时触发的init方法
     * @param {*} data 传入data
     * @return {*}
     */
    initData(data) {
      const orgForm = this.$options.data().form;
      this.form = { ...orgForm, ...data };
      if (this.form.id) {
        this.loadDictItem()
      }
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    // 获取字典子表 --字典项
    loadDictItem() {
      let data = this.qs.stringify({ id: this.form.id })
      API.loadDictionaryById(data).then(
        (resp) => {
          this.form = resp
          if (this.form.details.length) {
            this.form.details.sort((a, b) => {
              return a.sn - b.sn
            })
            this.form.details.forEach(
              (item, index) => {
                item.key = utils.uuid()
              }
            )
            this.form.details = [...this.form.details]
          }
        },
        (error) => {
          reject(error)
        }
      )
    },
    analysisText() {
      if (!this.excleText) {
        this.$message.warning(
          '暂无可解析的数据，请将数据复制到文本框中，再重试！'
        )
      } else {
        this.analysis(this.excleText)
      }
    },
    analysis(data) {
      let dictionaryId = ''
      if (this.form && this.form.id) {
        form = this.form.id
      }

      let str = data.toString()
      let tempArr = str.split('\n')
      let addData = tempArr.map((item, index) => {
        let line = item.split('\t')
        return {
          dictionaryId,
          name: line[0],
          value: line[1],
          sn: line[2],
          flag: -1,
          key: new Date().getTime() + index,
        }
      })

      addData = addData.filter((item) => {
        if (item.name || item.value || item.sn) {
          return true
        } else {
          return false
        }
      })
      this.form.details.splice(0, addData.length, ...addData)
      console.log(addData, 'tempArr')
    },
    handleAdd() {
      let length = this.form.details.length
      let dictionaryId = ''
      if (this.form && this.form.id) {
        dictionaryId = this.form.id
      }
      this.form.details.push({
        dictionaryId,
        name: '',
        value: '',
        sn: length + 1,
        flag: -1,
        key: utils.uuid(),
      })
    },
    handleDictItemDel() {
      // 非草稿状态不可删除
      // 区别有id 没得id
      if (!this.multipleSelection.length) {
        this.$message.warning('请选择要删除得数据')
        return
      } else {
        // 过滤出草稿状态得数据
        let initDictItem = this.multipleSelection.filter(
          (item) => item.flag == -1
        )
        if (!initDictItem.length) {
          this.$message.warning('启用或禁用状态的数据，不可删除！')
        } else {
          let msg =
            '如存在未保存的字典成员,请先保存！如继续此操作未保存的编辑将被删除,是否继续?'
          this.$confirm(msg, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              // 收集已提交的数据id
              let ids = [],
                keys = []
              initDictItem.forEach((item) => {
                keys.push(item.key)
                if (item.id) {
                  ids.push(item.id)
                }
              })
              // 本地删除草稿的数据
              const dataSource = [...this.form.details]
              let dataTemp = dataSource.filter(
                (item) => !keys.includes(item.key)
              )
              this.form.details = dataTemp

              if (ids.length > 0) {
                // 提交数据
                let params = this.qs.stringify({
                  ids: ids.join(','),
                })
                API.deleteDictItem(params).then(() => {
                  this.loadDictItem()
                  this.$message.success('删除成功')
                })
              }
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: `已取消删除`,
              })
            })
        }
      }
    },
    handleDictItemFlag(status) {
      let hasNoSave = false
      if (this.multipleSelection.length <= 0) {
        this.$message.warning('请选择至少一条数据！')
        return
      } else {
        let ids = []
        this.multipleSelection.forEach((item) => {
          if (!item.id) {
            hasNoSave = true
            return
          }
          ids.push(item.id)
        })
        if (ids.length <= 0) {
          this.$message.warning('所选数据未保存，不能进行该操作！')
          return
        }
        let query = {
          ids: ids.join(','),
          status,
        }
        let param = this.qs.stringify(query, {
          indices: false,
        })
        let tag = status ? '启' : '禁'
        let msg
        if (hasNoSave) {
          msg =
            '存在未保存的字段成员,请先保存！如继续此操作未保存的编辑将被清除,是否继续?'
        } else {
          msg = `确定${tag}用选中数据,是否继续?`
        }
        this.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            // 调用接口 提交数据
            API.updateDictItemStatus(param).then(() => {
              this.loadDictItem()
              this.$message.success(
                `${status ? '启用' : '禁用'}成功`
              )
            })
          })
          .catch((err) => {
            console.log(err)
            this.$message({
              type: 'info',
              message: `已取消${status ? '启用' : '禁用'}`,
            })
          })
      }
    },
    handleIndex() {
      if (this.snChange == null) {
        this.$message.warning('字典项排序号无更改')
      } else {
        API.updateDictItemSequence(this.snChange).then(() => {
          this.loadDictItem()
          this.$message.success('排序号更新成功!')
        })
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 子表改变排序号
    changeSN(row) {
      if (this.snChange == null) {
        this.snChange = {}
        this.snChange[row.id] = row.sn
      } else {
        this.snChange[row.id] = row.sn
      }
      console.log(this.snChange)
    },
    onCancel() {
      this.form = {
        kindId: 1,
        name: '',
        code: '',
        memo: '',
        details: [],
        treeId: '',
      }
      this.excleText = '';
      this.visible = false;
    },
    onConfirm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.form.details.length) {
            let TempArr = [...this.form.details]
            TempArr.forEach((item) => {
              delete item.key
            })
            this.form.details = TempArr
          }

          this.form.kindId = 1

          this.loading = true;

          try {
            const { state, message } = await API.saveEnumDict(this.form);
            if (state) {
              this.$message.success('保存成功');
            }
          } catch (err) {
            this.$message.warning(err || '保存字典值失败！');
          } finally {
            this.loading = false;
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
// ::v-deep .app-dialog-content {
//   height: 28vh !important;
// }
::v-deep {
  .el-table td.el-table__cell {
    padding: 0;
  }

  .el-form-item {
    margin: 18px 0;
  }
}
</style>
