<template>
  <el-dialog
    :title="!dataForm.contractId ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="100px" size="mini">
      <el-row>
        <el-col :span="12">
          <el-form-item label="合同类型" prop="contractType">
            <el-select v-model="dataForm.contractType" placeholder="合同类型" style="width: 100%;">
              <el-option
                v-for="item in contractTypeOpt"
                :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="contractNumber">
            <el-input v-model="dataForm.contractNumber" placeholder="合同编号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否是主合同" prop="isMaster">
            <el-switch
              v-model="dataForm.isMaster"
              active-color="#409EFF"
              inactive-color="#F56C6C"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否验收" prop="isAcceptance">
            <el-switch
              v-model="dataForm.isAcceptance"
              active-color="#409EFF"
              inactive-color="#F56C6C"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户" prop="clientId">
            <el-select v-model="dataForm.clientId" placeholder="客户" style="width: 100%;">
              <el-option
                v-for="item in clientIdOpt"
                :key="item.clientId"
                :label="item.clientName"
                :value="item.clientId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="dataForm.remarks" placeholder="备注"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-button size="mini" type="primary" @click="addMaterial">选择物料</el-button>
        </el-col>
        <el-col :span="12">
          <el-form-item label="总计">
            <el-input v-model="dataForm.totalSum" placeholder="总计" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table
      :data="materData"
      border
      size="mini"
      max-height="200"
      style="width: 100%;">
      <el-table-column
        prop="materialCode"
        header-align="center"
        align="center"
        label="物料编码">
      </el-table-column>
      <el-table-column
        prop="materialName"
        header-align="center"
        align="center"
        label="物料名称">
      </el-table-column>
      <el-table-column
        prop="materialType"
        header-align="center"
        align="center"
        label="物料类型">
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        width="120"
        label="单价">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.price" placeholder="请输入单价" @input="calculateTotal(scope.$index)" @blur="calculateTotal(scope.$index)"></el-input>
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        width="120"
        label="价格系数">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.coefficient" placeholder="请输入价格系数"></el-input>
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        width="120"
        label="对外价格">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.externalPrice" placeholder="请输入对外价格"></el-input>
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        width="120"
        label="数量">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.quantity" placeholder="请输入数量" @input="calculateTotal(scope.$index)" @blur="calculateTotal(scope.$index)"></el-input>
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        label="总价">
        <template slot-scope="scope">
          {{ scope.row.total }}
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="80"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="deleteHandle(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" @click="visible = false">取消</el-button>
      <el-button size="mini" type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
    <el-dialog
      title="选择物料"
      :visible.sync="innerVisible"
      append-to-body>
        <el-form size="mini" :inline="true" :model="innerDataForm" @keyup.enter.native="getDataList()">
          <el-form-item>
            <el-input v-model="innerDataForm.key" placeholder="参数名" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="getDataList()">查询</el-button>
          </el-form-item>
        </el-form>
        <el-table
          :data="dataList"
          border
          size="mini"
          max-height="400"
          v-loading="dataListLoading"
          @selection-change="selectionChangeHandle"
          style="width: 100%;">
          <el-table-column
            type="selection"
            header-align="center"
            align="center"
            width="50">
          </el-table-column>
          <el-table-column
            prop="materialId"
            header-align="center"
            align="center"
            label="id">
          </el-table-column>
          <el-table-column
            prop="materialCode"
            header-align="center"
            align="center"
            label="物料编码">
          </el-table-column>
          <el-table-column
            prop="materialName"
            header-align="center"
            align="center"
            label="物料名称">
          </el-table-column>
          <el-table-column
            prop="materialType"
            header-align="center"
            align="center"
            label="物料类型">
          </el-table-column>
          <el-table-column
            prop="isOn"
            header-align="center"
            align="center"
            label="是否启用">
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="innerVisible = false">取消</el-button>
          <el-button size="mini" type="primary" @click="innerSubmit">确定</el-button>
        </span>
    </el-dialog>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
        innerVisible: false,
        dataForm: {
          contractId: 0,
          contractType: '',
          isMaster: 0,
          contractNumber: '',
          clientId: '',
          isAcceptance: 0,
          remarks: '',
          totalSum: 0
        },
        dataRule: {
          contractType: [
            { required: true, message: '合同类型不能为空', trigger: 'blur' }
          ],
          contractNumber: [
            { required: true, message: '合同编号不能为空', trigger: 'blur' }
          ],
          clientId: [
            { required: true, message: '客户不能为空', trigger: 'blur' }
          ]
        },
        innerDataForm: {
          key: ''
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        materData: []
      }
    },
    props: {
      contractTypeOpt: Array,
      clientIdOpt: Array
    },
    watch: {
      materData: {
        deep: true,
        handler() {
          this.calculateTotalSum()
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.contractId = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          this.materData = []
          if (this.dataForm.contractId) {
            this.$http({
              url: this.$http.adornUrl(`/flow/contract/list/${this.dataForm.contractId}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.contractType = data.contract.contractType
                this.dataForm.isMaster = data.contract.isMaster
                this.dataForm.contractNumber = data.contract.contractNumber
                this.dataForm.clientId = data.contract.clientId
                this.dataForm.materialJson = data.contract.materialJson
                this.dataForm.isAcceptance = data.contract.isAcceptance
                this.dataForm.remarks = data.contract.remarks
              }
            })
          }
        })
      },
      addMaterial () {
        this.innerVisible = true
        this.getDataList()
      },
      calculateTotal(index) {
        const row = this.materData[index]
        const price = parseFloat(row.price) || 0
        const quantity = parseFloat(row.quantity) || 0
        row.total = price * quantity
      },
      calculateTotalSum() {
        this.dataForm.totalSum = this.materData.reduce((sum, row) => sum + parseFloat(row.total || 0), 0)
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/flow/contract/${!this.dataForm.contractId ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'contractId': this.dataForm.contractId || undefined,
                'contractType': this.dataForm.contractType,
                'isMaster': this.dataForm.isMaster,
                'contractNumber': this.dataForm.contractNumber,
                'clientId': this.dataForm.clientId,
                'materialJson': JSON.stringify(this.materData),
                'isAcceptance': this.dataForm.isAcceptance,
                'remarks': this.dataForm.remarks,
                'totalSum': this.dataForm.totalSum
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/material/material/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'key': this.dataForm.key
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      innerSubmit () {
        this.innerVisible = false
        this.materData = [...this.materData, ...this.dataListSelections]
      },
      deleteHandle(index) {
        this.materData.splice(index, 1)
      }
    }
  }
</script>

<style scoped>
.el-pagination {
  margin-top: 15px;
  text-align: right;
}
</style>
