<!--
 * @Author: @liulin
 * @Date: 2022-06-06 15:02:11
 * @LastEditors: Please set LastEditors
-->
<template>
  <at-table
    @load="loadData"
    :data="data"
    :page-result="pageResult"
    :dialogTitle="'详情'"
    :dialogVisible="dialogVisible"
    @handleDialogCancel="handleDialogCancel"
    @handleDialogClose="handleDialogClose"
    @handleDialogSubmit="handleDialogSubmit"
    @row-dblclick="handleRowDBClick"
    ref="AtTable"
    v-loading="loading"
  >
    <template v-slot:searchInput>
      <el-form
        ref="searchForm"
        :model="searchForm"
        label-width="80px"
        class="search-top"
        @submit.native.prevent
      >
        <el-input
          v-model="searchForm.name"
          placeholder="请输入模板名称"
          :clearable="true"
          @keyup.enter.native="findinfo"
        />
        <el-button
          size="small"
          type="primary"
          class="el-icon-search search-btn"
          @click="findinfo"
          >查询</el-button
        >
        <el-button
          size="small"
          type="primary"
          plain
          class="el-icon-refresh search-btn"
          @click="handleReset"
          >重置</el-button
        >
      </el-form>
    </template>
    <template v-slot:operationBtn>
      <el-button
        size="small"
        type="primary"
        @click="handleAdd"
        icon="el-icon-plus"
        >添加</el-button
      >
      <ht-delete-button
        :url="deleteUrl"
        :htTable="$refs.AtTable"
        :requestMethod="'POST'"
        >删除</ht-delete-button
      >
    </template>
    <template>
      <el-table-column type="selection" width="55" align="center">
      </el-table-column>
      <el-table-column type="index" label="序号" width="55" align="center">
      </el-table-column>
      <!-- <el-table-column
        label="项目名称"
        align="center"
        prop="projectName"
        :show-overflow-tooltip="true"
      >
      </el-table-column> -->
      <el-table-column
        prop="name"
        label="模板名称"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        prop="describe"
        label="模板描述"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        prop="createName"
        label="创建人名称"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column label="操作 " width="180" align="center">
        <template v-slot="{row}">
          <!-- <el-dropdown
            size="mini"
            split-button
            @command="handleCommand"
            @click="handleCommand({row, command: 'preview'})"
          > -->
          <el-button type="'primary">
            <el-link
              type="primary"
              @click="handleCommand({row, command: 'preview'})"
            >
              <i class="el-icon-view">预览及导出</i>
            </el-link>
          </el-button>
          <!-- <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="{row: row, command: 'download'}">
                <el-link type="primary">
                  <i class="el-icon-download">导出</i>
                </el-link>
              </el-dropdown-item>
            </el-dropdown-menu> -->
          <!-- </el-dropdown> -->
        </template>
      </el-table-column>
      <view-defined-dialog ref="viewDefined"  />
    </template>
    <template v-slot:dialogContent>
      <el-form
        ref="form"
        v-form
        data-vv-scope="form"
        :model="form"
        :rules="formRules"
        label-width="100px"
        v-if="dialogVisible"
      >
        <el-collapse v-model="collapseActiveNames">
          <el-collapse-item name="1">
            <template slot="title">
              <span class="span-title">模板信息</span>
            </template>
            <!-- <el-row>
              <el-form-item label="项目名称" prop="projectName">
                <project-info-selector
                  v-model="form.projectId"
                  @select="select"
                  style="width: 100%"
                ></project-info-selector>
              </el-form-item>
            </el-row> -->
            <el-row>
              <el-form-item label="模板名称" prop="name">
                <el-input
                  v-model="form.name"
                  placeholder="请输入模板名称"
                  clearable
                ></el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="模板描述">
                <el-input
                  v-model="form.describe"
                  placeholder="请输入模板描述"
                  clearable
                  type="textarea"
                  rows="3"
                ></el-input>
              </el-form-item>
            </el-row>
          </el-collapse-item>
          <el-collapse-item name="2">
            <template slot="title">
              <span class="span-title">配置信息</span>
            </template>
            <div class="button">
              <el-button
                size="small"
                type="primary"
                @click="handleAddprops"
                icon="el-icon-plus"
                >添加字段</el-button
              >
            </div>
            <el-table
              :data="propsData"
              style="width: 100%"
              height="290px"
              id="propsTable"
            >
              <el-table-column
                label="序号"
                type="index"
                align="center"
                width="60"
              ></el-table-column>
              <el-table-column
                label="字段名称"
                align="center"
                prop="fieldName"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                label="字段编码"
                align="center"
                prop="field"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                label="计算方式"
                align="center"
                prop="calculationMethod"
                show-overflow-tooltip
              >
                <!-- validate="required" -->
                <template v-slot="{row}">
                  <dict-select
                    v-model="row.calculationMethod"
                    dictCode="zdytz-jsfs"
                    placeholder="请选择计算方式"
                    clearable
                    :disabled="!disabledKeys.includes(row.fieldTypeValue)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button
                    circle
                    plain
                    type="primary"
                    icon="el-icon-top"
                    size="mini"
                    @click="handleUp(scope.row, scope.$index)"
                  ></el-button>
                  <el-button
                    circle
                    plain
                    type="primary"
                    icon="el-icon-bottom"
                    size="mini"
                    @click="handleDown(scope.row, scope.$index)"
                  ></el-button>
                  <el-popconfirm
                    style="margin-left: 10px"
                    confirm-button-text="确定"
                    cancel-button-text="取消"
                    icon="el-icon-info"
                    icon-color="red"
                    title="确定删除吗？"
                    @confirm="handleDelFields(scope.row)"
                  >
                    <el-button
                      slot="reference"
                      circle
                      type="danger"
                      icon="el-icon-delete"
                      size="mini"
                    ></el-button>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
        </el-collapse>

        <!-- 模板配置 -->
        <user-defined-ledger-dialog
          ref="templeteConfigRef"
          @submitPropsData="submitPropsData"
        />
      </el-form>
    </template>
  </at-table>
</template>

<script>
import Sortable from 'sortablejs'
import utils from '@/hotent-ui-util'
import UserDefinedLedgerDialog from '@/components/dialog/UserDefinedLedgerDialog.vue'
import ViewDefinedDialog from '@/components/dialog/ViewDefinedDialog.vue'
export default {
  name: 'UserDefinedLedger',
  components: {
    UserDefinedLedgerDialog,
    ViewDefinedDialog,
  },
   props: {
    pid: {
      type: String,
      default: '',
    },
    isShow: {
      type: Boolean,
      default: true,
    },
    alias: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      data: [],
      pageResult: {
        pageSize: 10,
        pageNum: 1,
        total: 0,
      },
      dialogVisible: false,
      form: {},
      propsData: [],
      collapseActiveNames: ['1', '2'],
      searchForm: {
        name: '',
      },
      loading: false,
      formRules: {
        name: [{required: true, message: '请输入模板名称', trigger: 'blur'}],
        // projectName: [
        //   {required: true, message: '请选择项目名称', trigger: 'blur'},
        // ],
      },
      disabledKeys: ['2', '3', '4'],
    }
  },
  computed: {
    deleteUrl: function () {
      return window.context.cqxy + '/biz/menuFieldTemp/v1/delete'
    },
  },
  created() {},
  methods: {
    // select(val, arr) {
    //   this.form.projectName = arr.projectName
    //   this.form.projectId = arr.id
    // },
    //行拖拽
    rowDrop() {
      const tbody = document
        .getElementById('propsTable')
        .querySelector('.el-table__body-wrapper tbody')
      const _this = this
      Sortable.create(tbody, {
        onEnd({newIndex, oldIndex}) {
          let arr = []
          _this.propsData.forEach((item) => {
            arr.push(item)
          })
          arr[newIndex] = arr.splice(oldIndex, 1, arr[newIndex])[0]
          _this.propsData = arr
        },

        /* newDraggableIndex */
        // onEnd({newIndex, oldIndex}) {
        //   const oldRow = _this.propsData[oldIndex]
        //   const newRow = _this.propsData[newIndex]
        //   oldRow.oldDraggableIndex = newIndex
        //   newRow.newDraggableIndex = oldIndex
        //   let newRows
        //   let rows
        //   if (newIndex > oldIndex) {
        //     newRows = _this.propsData.slice(oldIndex, newIndex + 1)
        //     rows = _this.propsData.splice(oldIndex, newRows.length)
        //   } else if (newIndex == oldIndex) {
        //     return
        //   } else {
        //     newRows = _this.propsData.slice(newIndex, oldIndex + 1)
        //     rows = _this.propsData.splice(newIndex, newRows.length)
        //   }
        //   const firstRow = rows.splice(0, 1)[0]
        //   const lastRow = rows.splice(rows.length - 1, 1)[0]
        //   _this.propsData.splice(newIndex, 0, lastRow, ...rows, firstRow)
        // },
      })
    },
    loadData(param, cb) {
      let query = []
      let search = {
        name_: this.searchForm.name,
      }
      for (let i in search) {
        if (search[i]) {
          query.push({
            group: 'advance',
            operation: 'LIKE',
            property: i,
            relation: 'AND',
            value: search[i],
          })
        }
      }
      if (param.querys && param.querys.length) {
        param.querys.push(...query)
      } else {
        param.querys = query
      }
      this.$http
        .post('${cqxy}/biz/menuFieldTemp/v1/query', param)
        .then(
          (resp) => {
            let response = resp.data
            this.data = response.rows
            this.pageResult = {
              page: response.page,
              pageSize: response.pageSize,
              total: response.total,
            }
          },
          (error) => {
            reject(error)
          }
        )
        .finally(() => {
          if (cb) {
            cb()
          }
        })
    },
    handleDialogCancel() {
      this.dialogVisible = false
    },
    handleDialogClose() {
      this.dialogVisible = false
    },
    handleAdd() {
      this.dialogVisible = true
      this.form = {
        // projectName:'',
        // projectId:'',
        name: '',
        describe: '',
      }
      this.propsData = []
      this.$nextTick(() => {
        this.rowDrop()
      })
    },
    handleAddprops() {
      this.$refs.templeteConfigRef.show(this.propsData)
    },
    handleCommand(row) {
      this.loading = true
      if (row.command == 'preview') {
        let param = {
          id: row.row.id,
        }
        if(this.pid){
          param.projectId=this.pid
        }
        this.$http
          .post('${cqxy}/biz/menuFieldTemp/v1/getDataById', param)
          .then((res) => {
            this.loading = false
            let data=res.data.value
            data.id = row.row.id
            if(this.pid){
               data.projectId=this.pid
               data.projectName=this.$route.params.projectName
               data.flag=true
            }
            this.$refs.viewDefined.open(data)
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        this.$http
          .get('${cqxy}/biz/menuFieldTemp/v1/exportData?id=' + row.row.id)
          .then((res) => {
            this.loading = false
          })
          .catch((res) => {
            this.loading = false
          })
      }
    },
    handleUp(row, index) {
      if (index !== 0) {
        let targetItem = row // 当前Item
        let upItem = this.propsData[index - 1] // 前一个Item
        let targetIndex = this.propsData[index].orderIndex // 当前ItemIndex
        let upIndex = this.propsData[index - 1].orderIndex // 前一个ItemIndex
        // 交换orderIndex
        targetItem.orderIndex = upIndex
        upItem.orderIndex = targetIndex
        this.propsData.splice(index - 1, 2, targetItem, upItem)
      } else {
        this.$message.warning('已经处于置顶，无法上移')
      }
    },
    handleDown(row, index) {
      if (index !== this.propsData.length - 1) {
        let targetItem = row // 当前Item
        let downItem = this.propsData[index + 1] // 前一个Item
        let targetIndex = this.propsData[index].orderIndex // 当前ItemIndex
        let downIndex = this.propsData[index + 1].orderIndex // 前一个ItemIndex
        // 交换orderIndex
        targetItem.orderIndex = downIndex
        downItem.orderIndex = targetIndex
        this.propsData.splice(index, 2, downItem, targetItem)
      } else {
        this.$message.warning('已经处于置底，无法下移')
      }
    },
    handleDelFields(row) {
      let formData = new FormData()
      formData.append('ids', row.id)
      this.$http
        .post('${cqxy}/biz/menuCustomizeField/v1/delete', formData)
        .then((res) => {
          if (res.data.state) {
            let data = utils.deepClone(this.propsData)
            let target = data.filter((item) => item.id != row.id)
            this.propsData = target
            this.$message.success(res.data.message)
          } else {
            this.$message.error(res.data.message)
          }
        })
    },
    findinfo() {
      this.$refs.AtTable.load()
    },
    handleReset() {
      this.searchForm = {
        name: '',
      }
      this.$refs.AtTable.load()
    },
    submitPropsData(data) {
      this.propsData = this.deweight(data)
    },
    deweight(arr) {
      let map = new Map()
      for (let i of arr) {
        if (!map.has(i.id)) {
          map.set(i.id, i)
        }
      }
      return [...map.values()]
    },
    handleDialogSubmit() {
      let params = {
        ...this.form,
        menuCustomizeFieldList: this.propsData,
      }
      this.$refs.form.validate((bool) => {
        if (bool) {
          this.$http
            .post('${cqxy}/biz/menuFieldTemp/v1/save', params)
            .then((res) => {
              this.$message.success('保存成功')
              this.dialogVisible = false
              this.$refs.AtTable.load()
            })
        }
      })
    },
    handleRowDBClick(data) {
      this.loading = true
      this.$http
        .post('${cqxy}/biz/menuFieldTemp/v1/detail/' + data.id)
        .then((res) => {
          this.form = res.data.value
          this.dialogVisible = true
          this.propsData = this.form.menuCustomizeFieldList
          this.propsData.forEach((item) => {
            this.$set(item, 'calculationMethod', item.calculationMethod || '1')
          })
          this.loading = false
          this.$nextTick(() => {
            this.rowDrop()
          })
        })
        .catch((err) => {
          console.error(err)
          this.loading = false
        })
    },
    handleCloseViewDialog(done) {
      done()
    },
  },
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/common.scss';
.button {
  margin-left: 20px;
}
.span-title {
  font-size: 18px;
  &::before {
    content: ' ';
    margin-right: 5px;
    width: 5px;
    height: 20px;
    display: inline-block;
    background-color: #409eff;
    vertical-align: middle;
  }
}
/deep/ .el-input__suffix > .el-input__icon {
  display: none;
}
/deep/ .el-table--border th .cell {
  color: #000;
}

/deep/ .el-dialog__body {
  padding-top: 20px;
  padding-bottom: 20px;
}
table {
  width: 100%;
  border-collapse: collapse;
}

table,
table tr td {
  border: 1px solid #ebeef5;
}

table tr td {
  padding: 15px 10px;
  // text-align: center;
}
</style>
