<template>
  <div>
    <SearchBox ref="SearchBoxRef" formName="search" :formData="queryTmpHead" @PopupNo="PopupNo" @reset="reset">
    </SearchBox>

    <ButtonBar @search="handleSearchTmpHead"></ButtonBar>

    <el-card :body-style="cardBodyStyle">
      <el-tabs v-model="activeNameTop" type="border-card">
        <el-tab-pane label="合同模板头" name="master">
          <el-table :data="tableDataTmpHead" border highlight-current-row @row-click="handleRowClickTmpHead">
            <el-table-column type="index" label="序号" align="center" width="60">
              <template #default="scope">
                <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="true" prop="cmpNm" label="公司名称" header-align="center" align="center"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column v-if="true" prop="contTy" label="合同类型" header-align="center" align="center"
              show-overflow-tooltip>
              <template #default="{ row }">
                {{ dicList.CONTRACT_TYPE.find(item => item.dicCode === row.contTy)?.dicName }}
              </template>
            </el-table-column>
            <el-table-column v-if="true" prop="tempNm" label="模板名称" header-align="center" align="center"
              show-overflow-tooltip>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-card :body-style="cardBodyStyle" class="card-margin">
      <el-pagination :current-page="currentPageTmpHead" :page-size="pageSizeTmpHead" :page-sizes="pageSizesTmpHead"
        :total="totalRowsTmpHead" background="background" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChangeTmpHead" @current-change="handleCurrentChangeTmpHead">
      </el-pagination>
    </el-card>

    <el-card :body-style="cardBodyStyle">
      <el-tabs v-model="activeNameBottom" type="border-card" @tab-click="handleClickTabs">
        <el-tab-pane label="合同模板行" name="first">
          <el-button plain type="primary" @click="handleAdd" style="margin-bottom: 10px;">新增</el-button>
          <el-table :data="tableData" border highlight-current-row @selection-change="handleSelectionChange">
            <el-table-column type="index" label="序号" align="center" width="60">
              <template #default="scope">
                <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="true" prop="cmpNm" label="公司名称" width="200px" header-align="center" align="center"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column v-if="true" prop="tempTy" label="模板类型" width="100px" header-align="center" align="center"
              show-overflow-tooltip>
              <template #default="{ row }">
                {{ dicList.CONTRACT_TYPE.find(item => item.dicCode === row.tempTy)?.dicName }}
              </template>
            </el-table-column>
            <el-table-column v-if="false" prop="cmpCd" label="公司编码" header-align="center" align="center"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column v-if="true" prop="clsTitle" label="模板条款标题" header-align="center" align="center"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column v-if="true" prop="clsCont" label="模板条款内容" header-align="center" align="center"
              show-overflow-tooltip>
            </el-table-column>

            <el-table-column label="操作" header-align="center" align="center" width="200px">
              <template #default="scope">
                <el-button plain type="warning" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button plain type="danger" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-card :body-style="cardBodyStyle" class="card-margin">
      <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes" :total="totalRows"
        background="background" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>

    <el-dialog :close-on-click-modal="false" draggable :title="title" v-model="dialogVisible" width="800px" top="5vh"
      @open="openDialog">
      <el-form :model="form" label-width="120px" label-position="right" ref="ruleFormRef" :rules="rules">
        <el-form-item label="模板类型" prop="tempTy" class="custom-margin">
          <el-select v-model="form.tempTy" placeholder="请选择" clearable style="width: 200px;" class="dicSelect" disabled>
            <el-option v-for="item in dicList.CONTRACT_TYPE" :key="item.dicCode" :label="item.dicName"
              :value="item.dicCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="模板条款标题" prop="clsTitle" class="custom-margin">
          <el-input v-model="form.clsTitle" clearable style="width: 200px" disabled>
          </el-input>
        </el-form-item>
        <el-form-item label="模板条款内容" prop="clsCont" class="custom-margin">
          <el-input type="textarea" v-model="form.clsCont" clearable style="width: 500px; height: 100px;"
            rows="4"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button plain  type="success" @click="handleSave(ruleFormRef)">保存</el-button>
          <el-button plain type="danger" @click="handleCancelSave">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <PopupCotTmpClause ref="PopupRefTmpHead" @receive-from-child="retuTmpHead" :params="params"></PopupCotTmpClause>
  </div>
</template>

<script setup>
import ButtonBar from '@/components/ButtonBar.vue'
import SearchBox from "@/components/SearchBox.vue";
import PopupCotTmpClause from '@/views/cot/components/PopupCotTmpClause.vue';


import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance
} from 'vue'
import { Search } from '@element-plus/icons-vue'
const {
  proxy
} = getCurrentInstance()

import tools from '@/tools'
import { ElMessage } from 'element-plus';
const cardBodyStyle = ref(tools.style.card)
const inputStyle = ref(tools.style.input)

onMounted(() => {
  handleSearchTmpHead()
  getDictList()
})


const activeNameTop = ref('master')
const activeNameBottom = ref('first')


/**
 * 查询公司代码
 */
const userId = window.localStorage.getItem('userId')
const userCode = window.localStorage.getItem('userCode')
const userName = window.localStorage.getItem('userDesc')
const dept = JSON.parse(window.localStorage.getItem('dept'))
const deptTree = JSON.parse(window.localStorage.getItem('deptTree'))
/**
 * 查询公司代码
 */

/**
 *  查询字典
 */
const dicList = ref({
  CONTRACT_TYPE: [],
})
const getDictList = () => {
  var url = 'framework/Common/querySelectorList'
  var param = {
    type: JSON.stringify(['CONTRACT_TYPE'])
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      dicList.value = response.data.data
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
/**
 *  查询字典
 */


/**
 *   查询 -- 头
 */
const queryTmpHead = ref({
  contTy: '',
  tempNm: ''
})
const tableDataTmpHead = ref([])
const handleSearchTmpHead = () => {
  selectedRow.value = null
  currentPageTmpHead.value = 1
  getTableDataTmpHead()

}
const getTableDataTmpHead = () => {
  tableData.value = []

  var url = 'cot/TmpHead/query'
  var param = {
    page: currentPageTmpHead.value,
    rows: pageSizeTmpHead.value,
    params: JSON.stringify(queryTmpHead.value)
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      tableDataTmpHead.value = response.data.data.records
      totalRowsTmpHead.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}


/**
 * 分页
 */
const currentPageTmpHead = ref(1)
const totalRowsTmpHead = ref(0)
const pageSizesTmpHead = ref([5, 10, 20, 30, 40])
const pageSizeTmpHead = ref(5)
const handleSizeChangeTmpHead = (val) => {
  pageSizeTmpHead.value = val
  getTableDataTmpHead()
}
const handleCurrentChangeTmpHead = (val) => {
  currentPageTmpHead.value = val
  getTableDataTmpHead()
}
/**
 * 分页
 */

const selectedRow = ref(null)
const handleRowClickTmpHead = (row, column, even) => {
  selectedRow.value = row
  query.value.tempId = selectedRow.value.id
  getTableData()
}




/**
 *   查询
 */
const query = ref({
  tempId: '',
})
const tableData = ref([])
const handleSearch = () => {
  currentPage.value = 1
  getTableData()

}
const getTableData = () => {
  console.log(query.value)
  var url = 'cot/TmpLine/query'
  var param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(query.value)
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      tableData.value = response.data.data.records
      totalRows.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}


/**
 * 分页
 */
const currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([5, 10, 20, 30, 40])
const pageSize = ref(5)
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}
/**
 * 分页
 */


/**
 * 新增
 */
const title = ref('')
const dialogVisible = ref(false)
const form = ref({
  cmpCd: '',
  cmpNm: '',
  tempId: '',
  tempTy: '',
  tempName: '',
  addId: '',
	addCode: '',
	addName: '',
	addDeptId: '',
	addDeptCode: '',
	addDeptName: '',
	addTime: '',
	modifyCode: '',
  modifyName: '',
  conTmpClauseList: []
})
const ruleFormRef = ref()
const rules = reactive({
  contTy: [{
    required: true,
    message: '请输入合同类型',
    trigger: 'change' | 'blur'
  }],
  tempNm: [{
    required: true,
    message: '请输入模板名称',
    trigger: 'change' | 'blur'
  }]
})
const params = ref({
  cmpNm: '',
  clsType: '',
})
const PopupRefTmpHead = ref(null)
const handleAdd = () => {
  if (window.localStorage.getItem('dept') == JSON.stringify(new Array())) {
    ElMessage({
      type: 'warning',
      message: '请添加登录人所在公司'
    })
    return
  }

  if (selectedRow.value == null) {
    ElMessage({
      type: 'warning',
      message: '请先选择合同模版头！'
    })
    return
  }

  form.value = {
    cmpCd: selectedRow.value.cmpCd,
    cmpNm: selectedRow.value.cmpNm,
    tempId: selectedRow.value.id,
    tempTy: selectedRow.value.contTy,
    tempName: selectedRow.value.tempNm,
    addId: userId,
		addCode: userCode,
		addName: userName,
		addDeptId: dept[0].id,
		addDeptCode: dept[0].deptCode,
		addDeptName: dept[0].deptName,
		addTime: '',
		modifyCode: '',
  	modifyName: '',
    conTmpClauseList: []
  }

  title.value = '新增'

  params.value = {
    cmpNm: selectedRow.value.cmpNm,
    clsType: selectedRow.value.contTy,
  }
  PopupRefTmpHead.value.open()
}
const retuTmpHead = (val) => {
  form.value.conTmpClauseList = val
  handleSaveBatch()
}

/**
 * 新增
 */
/**
 * 保存、修改、删除
 */
const openDialog = () => {
}
const handleSave = (ruleFormRef) => {
  ruleFormRef.validate((valid, fields) => {
    if (valid) {
      var url = 'cot/TmpLine/save'
      var param = {
        json: JSON.stringify(form.value),
      }
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
          form.value = response.data.data
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          getTableData()
          dialogVisible.value = false
        } else {
          ElMessage({
            message: '操作失败' + response.data.msg,
            type: 'error'
          })
        }
      })

    } else {
      console.log('error submit!', fields)
    }
  })
}
const handleSaveBatch = () => {
  var url = 'cot/TmpLine/saveBatch'
  var param = {
    json: JSON.stringify(form.value),
  }
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      ElMessage({
        message: '保存成功',
        type: 'success',
      })
      getTableData()
      dialogVisible.value = false
    } else {
      ElMessage({
        message: '操作失败' + response.data.msg,
        type: 'error'
      })
    }
  })
}
const handleCancelSave = () => {
  dialogVisible.value = false
}
const handleEdit = (row) => {
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields()
  }

  title.value = '编辑'
  form.value = { ...row }
  form.value.modifyCode = userCode
  form.value.modifyName = userName
  dialogVisible.value = true
}
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定删除本条记录?',
    '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }
  )
    .then(() => {
      var url = 'cot/TmpLine/remove'
      var param = {
        id: row.id
      }
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getTableData()
        } else {
          ElMessage({
            type: 'error',
            message: '删除失败' + response.data.msg
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}
/**
 * 保存、修改、删除
 */

const multipleSelection = ref([])
const handleRemoveBatch = () => {
  console.log('handleRemoveBatch')

  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据!'
    })
    return
  }

  ElMessageBox.confirm('此操作将删除该数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    var ids = []
    multipleSelection.value.forEach((item, index) => {
      ids.push(item.id)
    })
    var url = 'cot/TmpLine/removeBatch'
    var param = {
      ids: JSON.stringify(ids)
    }
    proxy.$axios.post(url, param).then(response => {
      if (response.data.code == '0') {
        ElMessage({
          type: 'success',
          message: '操作成功!',
        });
        getTableData()
        dialogVisible.value = false
      } else {
        ElMessage({
          type: 'error',
          message: '操作失败!' + response.data.msg
        });
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}
const handleEditBatch = () => {
  if (multipleSelection.value.length != 1) {
    ElMessage({
      type: 'warning',
      message: '请选择一条数据编辑!'
    })
    return
  }
  handleEdit(multipleSelection.value[0])
}
const handleUpload = () => {
  console.log('handleUpload')
}
const handleDownload = () => {
  console.log('handleDownload')
}
const handleImport = () => {
  console.log('handleImport')
}
const handleExport = () => {
  console.log('handleExport')
}

</script>

<style scoped>
.add-button {
  margin-right: 500px;

  /* 添加一些左边距，使按钮与表单项之间有间隔 */
}

.card-margin {
  margin-bottom: 30px;
  /* 根据需要调整距离 */
}

::v-deep .dicSelect .el-select__wrapper .el-select__selected-item {
  color: #a8abb2;
}
</style>