<template>
  <div class="app-container">
    <!--列表页面-->
    <div v-show="viewState == 1">
      <button-bar view-title="附加项目管理" ref="btnbar" :btndisabled="btndisabled" @btnhandle="btnHandle"/>
      <!--Start查询列表部分-->
      <div class="main-content">
        <div class="searchcon">
          <el-button size="small" class="searchbtn" @click="clicksearchShow">{{ searchxianshitit }}</el-button>
          <div v-show="isSearchShow" class="search">
            <el-form ref="listQueryform" :inline="true" :model="listQuery" label-width="100px" class="tab-header">
              <el-form-item label="项目名称">
                <el-input v-model="listQuery.params.aitemName" placeholder="" clearable/>
              </el-form-item>
            </el-form>
            <div class="btn" style="text-align: center;">
              <el-button type="primary" icon="el-icon-search" size="small" @click="handleFilter">查询</el-button>
              <el-button type="primary" icon="el-icon-refresh" size="small" @click="handleReset">重置</el-button>
            </div>
          </div>
        </div>
        <!--End查询列表部分-->
        <div class="listtop">
          <div class="tit">附加项目列表</div>
          <pageye v-show="list.length > 0" :total="listQuery.total" :page.sync="listQuery.current" :limit.sync="listQuery.size" class="pagination" @pagination="getList"/>
        </div>
        <!--Start 主页面主要部分 -->
        <div class="">
          <el-table :key="tableKey" v-loading="listLoading" :data="list" :border="true" style="width: 100%;" @selection-change="handleSelectionChange">
            <el-table-column type="selection" align="center" width="50"/>
            <el-table-column label="序号" type="index" width="80" :index="indexMethod" align="center"/>
            <el-table-column label="操作" width="180px" align="center">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="toEdit(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="aitemName" label="项目名称" align="center" />
            <el-table-column prop="aitemCode" label="拼音缩写" align="center" />
            <el-table-column prop="remarks" label="备注" align="center" />
            <el-table-column prop="price" label="销售金额" align="center" />
            <el-table-column prop="cost" label="成本" align="center" />
            <el-table-column prop="sortNo" label="排序" align="center" />
          </el-table>
        </div>
        <!--End 主页面主要部分-->
        <div class="pages">
          <div class="tit"/>
          <!-- 翻页 -->
          <pagination v-show="list.length > 0" :total="listQuery.total" :page.sync="listQuery.current" :limit.sync="listQuery.size" class="pagination" @pagination="getList"/>
        </div>
        <!--End查询列表部分-->
      </div>
    </div>
    <el-dialog center :visible.sync="dialogVisible" width="70%">
      <el-form ref="form_obj" :model="formobj" :rules="rules" class="formaddcopy02">
        <el-row style="border-top: 1px solid #E0E3EB">
          <el-col :span="12">
            <div class="span-sty"><span class="icon">*</span>项目名称</div>
            <el-form-item prop="aitemName"><el-input class="addinputInfo addinputw" v-model="formobj.aitemName" clearable placeholder="" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="span-sty">拼音缩写</div>
            <el-form-item><span class="addinputInfo">{{ formobj.aitemCode }}</span></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <div class="span-sty">备注</div>
            <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.remarks" clearable placeholder="" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="span-sty"><span class="icon">*</span>排序</div>
            <el-form-item prop="sortNo"><el-input class="addinputInfo addinputw" @keyup.native="formobj.sortNo = getNumber(formobj.sortNo, 0)" v-model="formobj.sortNo" clearable placeholder="" /></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <div class="span-sty"><span class="icon">*</span>销售价</div>
            <el-form-item prop="price"><el-input class="addinputInfo addinputw" @keyup.native="formobj.price = getNumber(formobj.price, 2)" v-model="formobj.price" clearable placeholder="" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="span-sty"><span class="icon">*</span>成本</div>
            <el-form-item prop="cost"><el-input class="addinputInfo addinputw" @keyup.native="formobj.cost = getNumber(formobj.cost, 2)" v-model="formobj.cost" clearable placeholder="" /></el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" size="small" @click="handleConfirm">确定</el-button>
        <el-button size="small" @click="handleClose">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/pagination'
import pageye from '@/components/pagination/pageye'
import ButtonBar from '@/components/ButtonBar'
import req from '@/api/basicinformation/additionitem'
import { getOrgSidByPath } from '@/api/Common/dictcommons'

export default {
  name: 'AdditionItem',
  components: {
    Pagination,
    pageye,
    ButtonBar
  },
  data() {
    return {
      dialogVisible: false,
      formobj: {
        createBySid: '',
        sid: '',
        sortNo: '',
        aitemCode: '',
        aitemName: '',
        remarks: '',
        price: '',
        cost: '',
        createOrgSid: '',
        useOrgSid: ''
      },
      rules: {
        aitemName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
        price: [{ required: true, message: '销售价不能为空', trigger: 'blur' }],
        sortNo: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
        cost: [{ required: true, message: '成本不能为空', trigger: 'blur' }],
      },
      btndisabled: false,
      btnList: [
        {
          type: 'primary',
          size: 'small',
          icon: 'plus',
          btnKey: 'toAdd',
          btnLabel: '新增'
        },
        {
          type: 'danger',
          size: 'small',
          icon: 'del',
          btnKey: 'doDel',
          btnLabel: '删除'
        },
        {
          type: 'info',
          size: 'small',
          icon: 'cross',
          btnKey: 'doClose',
          btnLabel: '关闭'
        }
      ],
      isSearchShow: false,
      searchxianshitit: '显示查询条件',
      viewState: 1, // 1、列表 2、新增 3、编辑 4、查看
      tableKey: 0,
      list: [],
      sids: [], // 用于导出的时候保存已选择的SIDs
      listLoading: false,
      // 翻页
      listQuery: {
        current: 1,
        size: 10,
        total: 0,
        params: {
          aitemName: '',
          orgPath: '',
          menuUrl: '',
          userSid: ''
        }
      }
    }
  },
  created() {
    // 初始化变量
    this.getList()
  },
  mounted() {
    this.$refs['btnbar'].setButtonList(this.btnList)
  },
  methods: {
    // 搜索条件效果
    clicksearchShow() {
      this.isSearchShow = !this.isSearchShow
      if (this.isSearchShow) {
        this.searchxianshitit = '隐藏查询条件'
      } else {
        this.searchxianshitit = '显示查询条件'
      }
    },
    btnHandle(btnKey) {
      console.log('XXXXXXXXXXXXXXX    ' + btnKey)
      switch (btnKey) {
        case 'toAdd':
          this.toAdd()
          break
        case 'doDel':
          this.doDel()
          break
        case 'doClose':
          this.doClose()
          break
        default:
          break
      }
    },
    // 信息条数 获取点击时当前的sid
    handleSelectionChange(row) {
      const aa = []
      row.forEach(element => {
        aa.push(element.sid)
      })
      this.sids = aa
    },
    // 表中序号
    indexMethod(index) {
      var pagestart = (this.listQuery.current - 1) * this.listQuery.size
      var pageindex = index + 1 + pagestart
      return pageindex
    },
    // 查询列表信息
    getList() {
      this.listLoading = true
      this.listQuery.params.userSid = window.sessionStorage.getItem('userSid')
      this.listQuery.params.menuUrl = this.$route.path
      this.listQuery.params.orgPath = window.sessionStorage.getItem('defaultOrgPath')
      req.listPage(this.listQuery).then(response => {
        this.listLoading = false
        if (response.success) {
          this.list = response.data.records
          this.listQuery.total = response.data.total
        } else {
          this.list = []
          this.listQuery.total = 0
        }
      })
    },
    // 查询按钮
    handleFilter() {
      this.listQuery.current = 1
      this.getList()
    },
    // 点击重置
    handleReset() {
      this.listQuery = {
        current: 1,
        size: 10,
        total: 0,
        params: {
          aitemName: '',
          orgPath: '',
          menuUrl: '',
          userSid: ''
        }
      }
      this.getList()
    },
    toAdd() {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
    },
    getNumber(val, limit) {
      val = val.replace(/[^0-9.]/g, '') // 保留数字
      val = val.replace(/^00/, '0.') // 开头不能有两个0
      val = val.replace(/^\./g, '0.') // 开头为小数点转换为0.
      val = val.replace(/\.{2,}/g, '.') // 两个以上的小数点转换成一个
      val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.'); // 只保留一个小数点
      /^0\d+/.test(val) ? val = val.slice(1) : '' // 两位以上数字开头不能为0
      const str = '^(\\d+)\\.(\\d{' + limit + '}).*$'
      const reg = new RegExp(str)
      if (limit === 0) {
        // 不需要小数点
        val = val.replace(reg, '$1')
      } else {
        // 通过正则保留小数点后指定的位数
        val = val.replace(reg, '$1.$2')
      }
      return val
    },
    toEdit(row) {
      this.dialogVisible = true
      req.fetchBySid(row.sid).then((res) => {
        if (res.success) {
          this.formobj = res.data
        }
      })
    },
    handleConfirm() {
      this.formobj.createBySid = window.sessionStorage.getItem('userSid')
      this.formobj.useOrgSid = window.sessionStorage.getItem('defaultOrgPath').substring(window.sessionStorage.getItem('defaultOrgPath').lastIndexOf('/') + 1)
      getOrgSidByPath({ orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((res) => {
        if (res.success) {
          this.formobj.createOrgSid = res.data
          this.$refs['form_obj'].validate((valid) => {
            if (valid) {
              req.saveOrUpdate(this.formobj).then((resp) => {
                if (resp.success) {
                  this.$message({ showClose: true, type: 'success', message: '保存成功' })
                  this.getList()
                  this.handleClose()
                }
              })
            }
          })
        }
      })
    },
    handleClose() {
      this.dialogVisible = false
      this.formobj = {
        createBySid: '',
        sid: '',
        sortNo: '',
        aitemCode: '',
        aitemName: '',
        remarks: '',
        price: '',
        cost: '',
        createOrgSid: '',
        useOrgSid: ''
      }
    },
    // 删除
    doDel() {
      if (this.sids.length === 0) {
        this.$message({ showClose: true, type: 'error', message: '请选择至少一条记录进行删除操作' })
        return
      }
      const tip = '请确认是否删除所选 ' + this.sids.length + ' 条记录?'
      this.$confirm(tip, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        req.deleteBySids(this.sids).then(resp => {
          if (resp.success) {
            this.$message({ type: 'success', message: resp.msg, showClose: true })
          }
          this.getList()
          loading.close()
        }).catch(e => {
          loading.close()
        })
      }).catch(() => {
      })
    },
    doClose() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.go(-1)
    }
  }
}
</script>
<style scoped>
.span-sty {
  width: 80px !important;
}
.addinputInfo {
  margin-left: 75px !important;
}
/deep/ .el-form-item__error {
  margin-left: 75px !important;
}
.formaddcopy02 .el-row .el-col /deep/ .el-form-item .addinputw {
  margin-left: 75px !important;
  width: calc(100% - 70px);
}
</style>
