<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
	  draggable
      width="1200px"
      @close="close()"
      @keyup.enter.native="doSubmit"
	  v-model="visible">
      <el-form size="large" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="method==='view'"
               label-width="150px">
        <el-row  :gutter="0">
          <el-col :span="12">
            <el-form-item label="模板名称" prop="tplName" :rules="[
                  {required: true, message:'请输入模板名称', trigger:'blur'}
                ]">
              <el-input v-model="inputForm.tplName" placeholder="请输入模板名称"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="公司" prop="companyId"
                          :rules="[
                   {required: true, message:'请选择公司', trigger:'blur'}
                 ]">
              <SelectTree
                ref="officeTree"
                :props="{
                    value: 'id',             // ID字段名
                    label: 'name',         // 显示名称
                    children: 'children'    // 子级字段名
                  }"
                :url="`/system-server/sys/office/treeData2?type=1`"
                :value="inputForm.companyId"
                :clearable="true"
                :accordion="true"
				size="large"
                @getValue="(value) => {inputForm.companyId=value}"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="业务标识" prop="bizCode"
                          :rules="[
                      {required: true, message:'请选择业务标识', trigger:'blur'}
                   ]">
              <el-select v-model="inputForm.bizCode" placeholder="请选择业务标识" style="width:100%;">
                <el-option
                  v-for="item in $dictUtils.getDictList('serial_biztype')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="起始序列号" prop="serialNum">
              <el-input v-model="inputForm.serialNum" placeholder="请输入起始序列号"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="序列号长度" prop="serialNumLen"
                          :rules="[
                   {required: true, message:'请输入序列号长度', trigger:'blur'}
                 ]">
              <el-input v-model="inputForm.serialNumLen" placeholder="请输入序列号长度"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="编号模板" prop="serialTpl"
                :rules="[
                  {required: true, message:'请输入编号模板', trigger:'blur'}
                ]">
              <el-input v-model="inputForm.serialTpl" :disabled="true" placeholder="请输入编号模板"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="编号示例" prop="serialTplEx"
                          :rules="[
                  {required: true, message:'请输入编号示例', trigger:'blur'}
                ]">
              <el-input v-model="inputForm.serialTplEx" :disabled="true" placeholder="请输入编号示例"></el-input>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row></el-row>
          <el-form-item style="margin-top: 20px" label="生成编号模板" prop="mouldList">
            <vxe-toolbar >
              <template #buttons>
                <vxe-button status="primary"  @click="insertEvent">新增</vxe-button>
              </template>
            </vxe-toolbar>
          </el-form-item>
		  <el-row  :gutter="15" >
			  <el-col :span="24">
				<vxe-table
				  border
				  show-footer
				  show-overflow
				  ref="xTable"
				  :key="detailKey"
				  class="vxe-table-element"
				  :data="mouldList"
				  :disabled="method==='view'"
				  style="margin-left: 5em"
				  highlight-current-row
				  :edit-config="{trigger: 'click', mode: 'row', showStatus: false, autoClear: true, icon: '#'}"
				>

				  <vxe-table-column field="type" title="变量名称" :edit-render="{name: '$select', options: $dictUtils.getDictList('variable_type')}">
					<template #edit="scope" >
					  <vxe-select v-model="scope.row.type" @change="variableValue(scope.row, scope.row.type)" transfer>
						<vxe-option
						  v-for="item in $dictUtils.getDictList('variable_type')"
						  :key="item.value"
						  :value="item.value"
						  :label="item.label">
						</vxe-option>
					  </vxe-select>
					</template>
				  </vxe-table-column>
				  <vxe-table-column field="value" title="变量值" :edit-render="{}">
					<template #edit="scope">
					  <el-input :disabled="scope.row.showType" v-model="scope.row.value" ></el-input>
					</template>
				  </vxe-table-column>
				  <vxe-table-column title="操作" width="100">
					<template v-slot="scope">
					  <el-button  type="danger" @click="removeEvent(scope.row,scope.$rowIndex)">删除</el-button>
					</template>
				  </vxe-table-column>
				</vxe-table>

			  </el-col>
		  </el-row>
      </el-form>
		<template #footer>
			<span  class="dialog-footer">
			  <el-button type="primary" v-if="method != 'view'" @click="generateTemplate()" >生成模板</el-button>
			  <el-button @click="close()" icon="el-icon-circle-close">关闭</el-button>
			  <el-button type="primary" v-if="method != 'view'" @click="doSubmit()" icon="el-icon-circle-check" v-noMoreClick>确定</el-button>
			</span>
		</template>

    </el-dialog>
  </div>
</template>

<script>
  import SerialnumTplService from '@/api/sys/SerialnumTplService'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  export default {
    data () {
      return {
        visable: false,
        gridData: [],
        radio: 0,
        tableData: [],
        dataList: [],
        dataListNew: [],
        title: '',
        method: '',
        isSubmit: false,
        visible: false,
        loading: false,
        returnForm: {
          id: '',
          tplName: '',
          companyId: '',
          bizCode: '',
          serialNum: '',
          serialNumLen: '',
          serialTpl: '',
          serialTplEx: ''
        },
        inputForm: {
          id: '',
          tplName: '',
          companyId: '',
          bizCode: '',
          serialNum: '',
          serialNumLen: '',
          serialTpl: '',
          serialTplEx: ''
        },
        mouldList: [],
		  detailKey: '',
        mould: {
          type: '',
          value: '',
          showType: false
        }
      }
    },
    components: {
      SelectTree
    },
    serialnumTplService: null,
    created () {
      this.serialnumTplService = new SerialnumTplService()
    },
    methods: {
      init (method, id) {
        this.method = method
        this.inputForm = {
          id: '',
          tplName: '',
          companyId: '',
          bizCode: '',
          serialNum: '',
          serialNumLen: '',
          serialTpl: '',
          serialTplEx: '',
          mouldList: [],
          mould: {
            type: '',
            value: ''
          }
        }
        this.inputForm.id = id
        if (method === 'add') {
          this.title = `新建基本信息`
        } else if (method === 'edit') {
          this.title = '修改基本信息'
        } else if (method === 'view') {
          this.showVi = false
          this.title = '查看基本信息'
        }
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          if (method === 'edit' || method === 'view') { // 修改或者查看
            this.loading = true
            this.serialnumTplService.findById(this.inputForm.id).then((data) => {
              this.inputForm = data
            })
          }
          this.loading = false
        })
      },
      // 表单提交
      doSubmit () {
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.serialnumTplService.save(this.inputForm).then((data) => {
              this.close()
              this.$message.success(data)
              this.$emit('refreshDataList')
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          }
        })
      },
      close () {
        this.$refs.inputForm.resetFields()
        this.visible = false
        this.showVi = true
        this.mouldList = []
      },
      // 排序
      sortChangeHandle (column) {
        this.orders = []
        if (column.order != null) {
          this.orders.push({column: this.$utils.toLine(column.prop), asc: column.order === 'ascending'})
        }
        this.refreshList()
      },
      deleteMsgById (row, index) {
        this.dataListNew.splice(index, 1)
        if (row.id !== null && row.id !== '' && row.id !== undefined) {
          this.ossService.deleteMsgById(row.id)
        }
      },
      tableRowClassName ({row, rowIndex}) {
        row.index = rowIndex
      },
      handleRadioChange (val) {
        if (val) {
          this.radio = val.index
        }
      },
      // 点击修改
      dbclickFun (cell) {
        this.onedit = false
      },
      // 新增
      async insertEvent () {
        if (this.inputForm.companyId === undefined || this.inputForm.companyId === '' || this.inputForm.companyId === null) {
          this.$message.error('请选择公司信息')
        } else if (this.inputForm.serialNumLen === undefined || this.inputForm.serialNumLen === '' || this.inputForm.serialNumLen === null) {
          this.$message.error('请输入序列号长度')
        } else {
          await this.$refs.xTable.insert().then((data) => {
            this.mouldList.push(data)
			  this.detailKey = Math.random()
          })
        }
      },
      // 删除
      removeEvent (row, rowIndex) {
        this.$refs.xTable.remove(row)
        this.mouldList.splice(rowIndex, 1)
      },
      // 变量值处理
      variableValue (row, type) {
        if (type === '1' || type === '2' || type === '11') {
          row.value = ''
          row.showType = true
        }
        if (type === '3' || type === '4' || type === '5' || type === '6') {
          row.showType = false
        }
        if (type === '7') {
          row.value = new Date().getFullYear()
          row.showType = true
        }
        if (type === '8') {
          let len = this.inputForm.serialNumLen
          let s = '0000000000000000'
          s = s.substring(0, len - 1)
          row.value = s + '1'
          row.showType = true
        }
        if (type === '9') {
          row.value = new Date().getMonth() + 1
          row.showType = true
        }
        if (type === '10') {
          row.value = new Date().getDate()
          row.showType = true
        }
      },
      // 生成模板
      generateTemplate () {
      	console.log('this.mouldList', this.mouldList)
        let list = this.mouldList
        let i = ''
        let j = ''
        list.forEach(obj => {
        	console.log('obj', obj)
          // 公司简称
          if (obj.type === '1') {
            i = i + '{spnm}'
          }
          // 分公司简称
          if (obj.type === '2') {
            i = i + '{brspnm}'
          }
          // 固定字符、业务类型、业务类型代码、业务类型的字
          if (obj.type === '3' || obj.type === '4' || obj.type === '5' || obj.type === '6') {
            i = i + obj.value
            j = j + obj.value
          }
          // 年度
          if (obj.type === '7') {
            i = i + '{year}'
            j = j + obj.value
          }
          // 流水号
          if (obj.type === '8') {
            i = i + '{serialNum}'
            j = j + obj.value
          }
          // 月度
          if (obj.type === '9') {
            i = i + '{month}'
            j = j + obj.value
          }
          // 日期
          if (obj.type === '10') {
            i = i + '{day}'
            j = j + obj.value
          }
          // 公司简称
          if (obj.type === '11') {
            i = i + '{replacement}'
          }
        })
        this.inputForm.serialTpl = i
        this.inputForm.serialTplEx = j
      }
    }
  }
</script>

<style>
  .tid_40 .vxe-body--column .vxe-cell{
    padding: 1px;
    text-align: center;
  }
  .tid_40 .vxe-header--row .col--last{
    text-align: center;
  }
  .tid_45 .vxe-body--column .vxe-cell{
    padding: 1px;
    text-align: center;
  }
  .tid_45 .vxe-header--row .col--last{
    text-align: center;
  }
  .vxe-select--panel {
    z-index: 9997 !important
  }
  .vxe-input--panel.type--date, .vxe-input--panel.type--month, .vxe-input--panel.type--week, .vxe-input--panel.type--year {
    z-index: 9998 !important
  }
</style>

<style scoped>
  .avatar{
    height: 100px;
  }
  .el-divider__text {
    font-weight: bold;
    font-size: 16px;
  }
</style>
