<template>
  <div>
    <el-form
      :disabled="mode==='detail'"
      inline
      ref="addForm"
      label-position="top"
      :model="formData"
      :rules="rules"
    >
      <el-collapse v-model="activeNames">
        <el-collapse-item title="基础信息" name="1">
          <el-form-item label="合同编号" prop="contractNo">
            <el-input v-model="formData.contractNo" :disabled="mode==='edit'"></el-input>
          </el-form-item>
          <el-form-item label="合同名称" prop="contractName">
            <el-input v-model="formData.contractName"></el-input>
          </el-form-item>
          <el-form-item label="合同类型" prop="contractType">
            <el-select v-model="formData.contractType" filterable placeholder="请选择">
              <el-option label="客户" value="CUSTOMER"></el-option>
              <el-option label="外租仓库" value="WH"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户" prop="customerCode">
            <PublicQuery
              title="客户"
              single
              :rowData.sync="ownerData"
              cfgKey="chgWmsCustomerByOwner"
              baseUrl="/chg_web/chgweb"
              :valueField.sync="formData.customerCode"
              :textField.sync="formData.ebcuNameCn"
            ></PublicQuery>
          </el-form-item>
          <el-form-item label="合同文件号" prop="fileNo">
            <el-input v-model="formData.fileNo"></el-input>
          </el-form-item>
          <el-form-item label="生效效日期" prop="effectiveDate">
            <el-date-picker
              v-model="formData.effectiveDate"
              type="datetime"
              value-format="yyyy-MM-dd hh:mm:ss"
              placeholder="选择日期时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="失效日期" prop="expirationDate">
            <el-date-picker
              v-model="formData.expirationDate"
              type="datetime"
              value-format="yyyy-MM-dd hh:mm:ss"
              placeholder="选择日期时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="延期日期" prop="extensionDate">
            <el-date-picker
              v-model="formData.extensionDate"
              type="datetime"
              value-format="yyyy-MM-dd hh:mm:ss"
              placeholder="选择日期时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="备注" prop="orderTime">
            <el-input></el-input>
          </el-form-item>
        </el-collapse-item>
      </el-collapse>
      <el-collapse v-model="activeNames" class="mrg-t">
        <el-collapse-item title="合同明细" name="2">
          <div>
            <el-button
              v-auth="50300030101"
              type="primary"
              @click="handleAddGoods"
              v-if="mode!=='detail'"
            >添加</el-button>
            <el-button
              v-auth="50300030101"
              type="primary"
              @click="handleDelGoods"
              v-if="mode!=='detail'"
            >移除</el-button>
            <el-button
              v-auth="50300030101"
              type="primary"
              @click="handleDelGoods"
              v-if="mode!=='detail'"
            >复制</el-button>
          </div>
          <div>
            <el-table :data="goodsList" @selection-change="handleSelectChange">
              <table-column type="selection" fixed align="center" width="55"></table-column>
              <table-column label="行号">
                <template slot-scope="scope">
                  <p class="blue" @click="doShowDetail(scope.row)">{{ scope.row.lineNo }}</p>
                </template>
              </table-column>
              <table-column label="费用种类" prop="feeCategory">
                <template
                  slot-scope="scope"
                >{{ $utils.keyMatcher(scope.row.feeCategory, $keys.charging.feeCategory).name }}</template>
              </table-column>
              <table-column label="作业环节" prop="tranType">
                <template
                  slot-scope="scope"
                >{{ $utils.keyMatcher(scope.row.tranType, $keys.charging.tranType).name }}</template>
              </table-column>
              <table-column label="费用名称" prop="feeNameCode">
                <template
                  slot-scope="scope"
                >{{ $utils.keyMatcher(scope.row.feeNameCode, $keys.charging.feeNameCode).name }}</template>
              </table-column>
              <table-column label="收支类型" prop="receivePay">
                <template
                  slot-scope="scope"
                >{{ $utils.keyMatcher(scope.row.receivePay, $keys.charging.receivePay).name }}</template>
              </table-column>
              <table-column label="计费基准" prop="chargeBase">
                <template
                  slot-scope="scope"
                >{{ $utils.keyMatcher(scope.row.chargeBase, $keys.charging.chargeBase).name }}</template>
              </table-column>
              <table-column label="单价" prop="price"></table-column>
              <table-column label="计费方式" prop="chargeType">
                <template
                  slot-scope="scope"
                >{{ $utils.keyMatcher(scope.row.chargeType, $keys.charging.chargeType).name }}</template>
              </table-column>
              <table-column label="计费阶梯方式" prop="ladderType"></table-column>
              <table-column label="级差类型" prop="classType"></table-column>
              <table-column label="生效条件" prop="sqlDesc">
                <template slot-scope="scope">
                  <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-edit"
                      plain
                      circle
                      @click="handleTakeEffect(scope.$index, scope.row)"
                    ></el-button>
                </template>
              </table-column>
              <table-column label="操作" width="100" fixed="right" v-if="mode!=='detail'">
                <template slot-scope="scope">
                  <el-tooltip content="编辑" placement="top">
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-edit"
                      plain
                      circle
                      @click="handleGoodsEdit(scope.$index, scope.row)"
                    ></el-button>
                  </el-tooltip>
                  <el-tooltip content="删除" placement="top">
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      plain
                      circle
                      @click="handleDelGoodsOne(scope.$index, scope.row)"
                    ></el-button>
                  </el-tooltip>
                </template>
              </table-column>
            </el-table>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-form>
    <div class="mrg-t" v-if="mode==='detail'">
      <el-collapse v-model="activeNames">
        <el-collapse-item title="操作信息" name="3">
          <div class="operation-info">
            <span>创建人登录名(姓名)：{{formData.creatorLoginName}}({{formData.creatorNameCn}})</span>
            <span>创建时间：{{formData.createTime}}</span>
            <span>修改人登录名(姓名)：{{formData.modifierLoginName}}({{formData.modifierNameCn}})</span>
            <span>修改时间：{{formData.modifyTime}}</span>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <div class="mrg-t" v-if="mode!=='detail'">
      <el-button v-auth="50600020219" type="primary" @click="submitForm">保存</el-button>
      <el-button v-auth="50600020220" type="primary" @click="submitAddForm">保存并新增</el-button>
    </div>
    <div class="mrg-t" v-if="mode==='detail'">
      <el-button v-if="formData.auditStatus==='00'" v-auth="50600020219" type="primary" @click="handlePoint('auditContractEntity')">审核</el-button>
      <el-button v-if="formData.auditStatus!=='00'" v-auth="50600020220" type="primary" @click="handlePoint('cancelAuditContractEntity')">取消审核</el-button>
      <el-button v-if="formData.auditStatus!=='00'" v-auth="50600020219" type="primary" @click="handlePoint('chargeAgain')">重新计费</el-button>
    </div>
    <contract-form
      :goodsFormVisible="goodsFormVisible"
      :currentRow="goodsEditRow"
      :rowIndex="rowIndex"
      :editBool="editBool"
      :levelList="levelList"
      @close="close"
      @handleConfirm="handleConfirm"
      @handleConfirmAdd="handleConfirmAdd"
      @editOK="editOK"
    ></contract-form>
    <contract-detail
      :currentDate="currentDate"
      :dialogVisible="dialogVisible"
      @dialogClose="dialogClose"
    ></contract-detail>

    <take-effect
    :takeFormVisible="takeFormVisible"
    :levelList="levelList"
    :condList="condList"
    :currentRow="goodsEditRow"
    @close="takeFormVisible=false"
    @handleReGetList="handleReGetList">
    </take-effect>

  </div>
</template>
<script>
import ContractForm from './childrenForm/goods-form'
import ContractDetail from './childrenForm/contract_detail'
import TakeEffect from './childrenForm/take-effect'

export default {
  components: {
    ContractForm,
    ContractDetail,
    TakeEffect,
  },
  created () {
    this.mode = this.$route.params.mode || 'create'
    if (this.mode === 'edit' || this.mode === 'detail') {
      this.formData = this.$route.params[0]
      this.goodsList = this.$route.params[1]
    }
    if (this.mode === 'copy') {
      this.formData = this.$route.params[0]
    }
  },
  data () {
    return {
      currentDate: {},
      dialogVisible: false,
      needRefresh: false, // 是否需要父路由刷新
      mode: 'create', // 模式
      activeNames: ['1', '2', '3'],
      formData: {},
      ownerData: {},
      goodsList: [],
      singlList: [],
      levelList: [],
      condList: [],
      goodsFormVisible: false,
      takeFormVisible: false,
      rowIndex: null,
      editBool: false,
      electedIds: '',
      goodsEditRow: {},
      cacheIds: [],
      rules: {
        contractNo: [
          { required: true, message: '合同编号必填', trigger: 'blur' }
        ],
        contractName: [
          { required: true, message: '合同名称必填', trigger: 'blur' }
        ],
        contractType: [
          { required: true, message: '合同类型必填', trigger: 'blur' }
        ],
        customerCode: [
          { required: true, message: '客户必填', trigger: 'blur' }
        ],
        effectiveDate: [
          { required: true, message: '生效日期必填', trigger: 'blur' }
        ],
        expirationDate: [
          { required: true, message: '失效日期必填', trigger: 'blur' }
        ]
      }
    }
  },
  props: {
  },
  methods: {

    // 发送保存数据
    psotList () {
      const url = this.$API.charging.contract.addList
      const formData = this.formData
      const formatData = {
        ...formData,
        wmContractDetailEntityBeanList: this.singlList,
        deleteLineNos: [],
        deleteClassJobIds: []
      }
      const param = {
        wmContractEntity: JSON.stringify(formatData)
      }
      this.$https.post(url, param).then(res => {
        if (res.success) {
          this.$emit('saveOK')
        }
      })
    },

    // 保存
    submitForm () {
      this.$refs.addForm.validate((vaild) => {
        if (vaild) {
          this.psotList()
          this.$nextTick(() => {
            this.$refs.addForm.resetFields()
            this.$router.back()
          })
        } else {
          return false
        }
      })
    },

    // 保存并新增
    submitAddForm () {
      this.$refs.addForm.validate((vaild) => {
        if (vaild) {
          this.psotList()
          this.$nextTick(() => {
            this.$refs.addForm.resetFields()
          })
        } else {
          return false
        }
      })
    },
    // 打开合同弹窗
    handleAddGoods () {
      const url = this.$API.charging.getPoor
      const param = {}
      this.$https.post(url, param).then(res => {
        this.goodsFormVisible = true
        this.editBool = true
        this.$nextTick(() => {
          this.levelList = res.rows
        })
      })
    },
    // 关闭合同明细
    close () {
      this.goodsFormVisible = !this.goodsFormVisible
    },
    // 展示合同明细
    doShowDetail (data) {
      this.dialogVisible = true
      this.currentDate = data
    },
    dialogClose () {
      this.dialogVisible = !this.dialogVisible
    },
    // 确认
    handleConfirm (list) {
      this.goodsList.push(list)
      this.singlList.push(list)
      this.goodsFormVisible = false
      this.$emit('toGetList')
    },
    // 确认并添加
    handleConfirmAdd (list) {
      this.goodsList.push(list)
    },
    // 合同信息保存成功
    editOK (row, index) {
      this.$set(this.goodsList, index, row)
      this.singlList.push(row)
      this.goodsFormVisible = false
      this.editBool = false
    },

    // 删除多行
    handleDelGoods () {
      const url = this.$API.stockIn.preReceiving.delGoodsList
      const param = { asnNo: this.formData.asnNo, lineNos: this.selectedIds }
      if (this.mode === 'edit') {
        this.$https.post(url, param).then(res => {
          if (res.success) {
            this.cacheIds = this.selectedIds.split(',').concat(this.cacheIds)
            this.goodsList = this.goodsList.filter((item, index) => {
              if (!item.isChecked) return item
            })
          }
        })
      } else {
        this.goodsList = this.goodsList.filter((item, index) => {
          if (item.isChecked) return item
        })
      }
    },
    //  编辑
    handleGoodsEdit (index, row) {
      let data = Object.assign({ isChecked: 'false' }, row)
      const url = this.$API.charging.getPoor
      const param = { contractNo: this.formData.contractNo, lineNo: row.lineNo }
      this.$https.post(url, param).then(res => {
        this.goodsFormVisible = true
        this.editBool = true
        this.$nextTick(() => {
          this.levelList = res.rows
          this.goodsEditRow = data
          this.rowIndex = index
        })
      })
    },
    // 删除单行
    handleDelGoodsOne (index, row) {
      const url = this.$API.charging.contract.delList
      this.selectedIds = row.lineNo
      this.cacheIds = this.selectedIds.split(',').concat(this.cacheIds)
      const param = { asnNo: row.asnNo, lineNos: this.selectedIds }
      if (this.mode === 'edit') {
        this.$https.post(url, param).then(res => {
          if (res.success) {
            this.goodsList.splice(index, 1)
          }
        })
      } else {
        this.goodsList.splice(index, 1)
      }
    },

    getData (url, param) {
      return this.$https.post(url, param)
    },

    handleTakeEffect (index, row) {
      const url = this.$API.charging.getPoor
      const condUrl = this.$API.charging.getDetailCond
      const param = { contractNo: this.formData.contractNo, lineNo: row.lineNo }
      this.$https.all([this.getData(url, param), this.getData(condUrl, param)]).then(res => {
        this.takeFormVisible = true
        this.$nextTick(() => {
          this.goodsEditRow = row
          this.levelList = res[0].rows
          this.condList = res[1].rows
        })
      })
    },

    reGetList () {
      const headUrl = this.$API.charging.contract.query
      const listUrl = this.$API.charging.contract.queryDetail
      const param = { contractNo: this.formData.contractNo }

      this.$https.all([this.getData(headUrl, param), this.getData(listUrl, param)]).then(res => {
        this.formData = res[0].rows[0]
        this.goodsList = res[1].rows
      })
    },

    handleReGetList (row) {
      const condUrl = this.$API.charging.getDetailCond
      const param = { contractNo: this.formData.contractNo, lineNo: row.lineNo }
      this.$https.post(condUrl, param).then(res => {
        this.condList = res.rows
      })
    },

    handlePoint (urlKey) {
      const url = this.$API.charging.contract[urlKey]
      const param = { contractNos: JSON.stringify([this.formData.contractNo]) }
      this.$https.post(url, param).then(res => {
        this.reGetList()
      })
    },

    handleSelectChange (selection) {
      this.selectedIds = selection.map(item => item.lineNo).join(',')
    }
  },
  watch: {
    rowData: {
      handler (item) {
        this.formData = { ...item }
      },
      deep: true
    },
    ownerData: {
      handler (item) {
        this.formData.ebcuNameCn = item.ebcuNameCn
      },
      deep: true
    }
  },
  beforeRouteLeave (to, from, next) {
    this.needRefresh && (to.meta.needRefresh = true)
    next()
  },
}
</script>
<style scoped >
.mrg-t {
  margin-top: 20px;
}
.blue {
  cursor: pointer;
  color: #0682ea;
}
</style>
