<template>
  <div>
    <div style="padding: 10px; margin-bottom: 80px">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
          <span style="font-weight: bold; font-size: 18px">客户信息</span>
          <el-divider />
          <el-row>
            <el-col :span="6">
              <el-form-item label="客户" prop="clientName">
                <el-input v-model="form.clientName" disabled placeholder="请选择客户" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户手机号" prop="clientPhone">
                <el-input v-model="form.clientPhone" disabled placeholder="客户手机号" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="证件类型" prop="clientCertificateType">
                <el-select v-model="form.clientCertificateType" disabled placeholder="证件类型">
                  <el-option v-for="item in dict.type.zhengjianleixing" :key="item.value" :value="parseInt(item.value)" :label="item.label" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="证件号" prop="clientCertificateNumber">
                <el-input v-model="form.clientCertificateNumber" disabled placeholder="请输入证件号" />
              </el-form-item>
            </el-col>
          </el-row>
          <span style="font-weight: bold; font-size: 18px">报修信息</span>
          <el-divider />
          <el-table v-loading="loading" :data="form.settlementRepairFormList">
            <el-table-column label="序号" align="center" type="index" fixed="left" />
            <el-table-column label="报修单号" align="center" prop="repairNumber" width="140px" fixed="left" />
            <el-table-column label="客户类型" align="center" prop="repairNumber" fixed="left">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.client_type" :value="scope.row.client.type"/>
              </template>
            </el-table-column>
            <el-table-column label="客户名称" align="center" prop="client.name" width="120px" fixed="left" show-overflow-tooltip/>
            <el-table-column label="联系方式" align="center" prop="client.phone" min-width="130px" show-overflow-tooltip />
            <el-table-column label="车辆品牌" align="center" prop="car.carBrand" />
            <el-table-column label="车牌号" align="center" prop="car.plateNumber" width="110"/>
            <el-table-column label="总工时" align="center" prop="totalActualTime" />
            <el-table-column label="工时费用（元）" align="center" prop="totalActualTimeMoney" min-width="120px" />
            <el-table-column label="材料费用（元）" align="center" prop="totalMaterialMoney" min-width="120px" />
            <el-table-column label="拖车费用（元）" align="center" prop="trailerMoney" min-width="120px" />
            <el-table-column label="结算总价（元）" align="center" prop="totalMoney" min-width="120px" />
            <el-table-column label="交工时间" align="center" prop="deliveryTime" min-width="150px" />
            <el-table-column label="结算时间" align="center" prop="settlementTime" min-width="150px" />
            <el-table-column label="登记时间" align="center" prop="createTime" min-width="150px" />
            <el-table-column label="登记人员" align="center" prop="createBy" min-width="100px" />
            <el-table-column label="是否交车" align="center" prop="isDelivery" fixed="right">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.repair_form_is_delivery" :value="scope.row.isDelivery" />
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="state" fixed="right">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.repair_form_state" :value="scope.row.state" />
              </template>
            </el-table-column>
<!--            <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">-->
<!--              <template slot-scope="scope">-->
<!--                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleRowDelete(scope.row)">删除</el-button>-->
<!--              </template>-->
<!--            </el-table-column>-->
          </el-table>
        <span style="font-weight: bold; font-size: 18px">结算信息</span>
        <el-divider />
        <el-row>
          <el-col :span="6">
            <el-form-item label="工时费" prop="totalActualTimeMoney">
              <el-input-number v-model="form.totalActualTimeMoney" :min="0" disabled style="width: 100%" placeholder="请输入工时费" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="原料费" prop="totalMaterialMoney">
              <el-input-number v-model="form.totalMaterialMoney" :min="0" disabled style="width: 100%" placeholder="请输入原料费" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="拖车费" prop="totalTrailerMoney">
              <el-input-number v-model="form.totalTrailerMoney" :min="0" disabled style="width: 100%" placeholder="请输入拖车费" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="总费用" prop="totalMoney">
              <el-input-number v-model="form.totalMoney" :min="0" disabled style="width: 100%" placeholder="请输入总费用" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!--          <el-col :span="6">-->
          <!--            <el-form-item label="结算单号" prop="settlementNumber">-->
          <!--              <el-input v-model="form.settlementNumber" disabled placeholder="自动生成" />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="6">
            <el-form-item label="工时费优惠" prop="manHourDiscountMoney">
              <el-input-number v-model="form.manHourDiscountMoney" :min="0" :max="form.totalActualTimeMoney" @change="moneyChange" style="width: 100%" placeholder="请输入工时费优惠" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="原料费优惠" prop="materialDiscountMoney">
              <el-input-number v-model="form.materialDiscountMoney" :min="0" :max="form.totalMaterialMoney" @change="moneyChange" style="width: 100%" placeholder="请输入原料费优惠" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="应收金额" prop="receivableMoney">
              <el-input-number v-model="form.receivableMoney" disabled :min="0" style="width: 100%" placeholder="请输入应收金额" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结算金额" prop="practicalMoney">
              <el-input-number v-model="form.practicalMoney" disabled :min="0" style="width: 100%" placeholder="请输入结算金额" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="form.paymentMethod" placeholder="请选择支付方式" style="width: 100%">
                <el-option v-for="item in dict.type.settlement_payment_method" :key="item.value" :value="parseInt(item.value)" :label="item.label" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结算时间" prop="settlementTime">
              <el-date-picker clearable
                              v-model="form.settlementTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              style="width: 100%"
                              placeholder="请选择结算时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="clientType == 2">
            <el-form-item label="付款账号" prop="paymentAccount">
              <el-input v-model="form.paymentAccount" placeholder="请输入付款账号"/>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="clientType == 2">
            <el-form-item label="账号名称" prop="paymentAccountName">
              <el-input v-model="form.paymentAccountName" placeholder="请输入账号名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="结算单备注" prop="settlementRemark">
              <el-input v-model="form.settlementRemark" type="textarea" rows="2" placeholder="请输入结算单备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="付款凭证" prop="paymentVoucher">
              <ImageUpload v-model="form.paymentVoucher" :limit="1" />
            </el-form-item>
          </el-col>
        </el-row>
        <span style="font-weight: bold; font-size: 18px">操作人信息</span>
        <el-divider />
        <el-row>
          <el-col :span="6">
            <el-form-item label="操作人" prop="createBy">
              <el-input v-model="form.createBy" placeholder="请输入操作人" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="操作时间" prop="createTime">
              <el-date-picker v-model="form.createTime" type="datetime" style="width: 100%" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择操作时间" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div slot="footer" class="footer-container">
      <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import { getRepairForm } from '@/api/business/repairForm'
import { listClient } from '@/api/business/client'
import {
  addSettlementMaintain,
  delSettlementMaintain,
  updateSettlementMaintain
} from '@/api/business/settlementMaintain'
import { formatDate } from '@/utils'

export default {
  name: "SettlementMaintainAdd",
  dicts: ['client_type', 'zhengjianleixing', 'settlement_payment_method', 'repair_form_is_delivery','repair_form_state', 'repair_form_settlement_state'],
  props: {
    clientType:{}
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      repairFormId: undefined,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报修单表格数据
      repairFormList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        repairNumber: undefined,
        plateNumber: undefined,
        clientName: undefined,
        clientPhone: undefined,
        isDelivery: undefined,
        stateList: [1, 2],
        settlementState: 1
      },
      // 表单参数
      form: {},
      deliveryTime: [],
      settlementRepairFormList: [],
      clientOpt: [],
      // 表单校验
      rules: {
        clientId: [
          { required: true, message: "客户不能为空", trigger: "blur" }
        ],
        clientName: [
          { required: false, message: "客户名称不能为空", trigger: "blur" }
        ],
        clientPhone: [
          { required: false, message: "客户手机号不能为空", trigger: "blur" }
        ],
        clientType: [
          { required: false, message: "客户类型不能为空", trigger: "change" }
        ],
        clientCertificateType: [
          { required: false, message: "证件类型不能为空", trigger: "change" }
        ],
        clientCertificateNumber: [
          { required: false, message: "证件号不能为空", trigger: "blur" }
        ],
        manHourDiscountMoney: [
          { required: true, message: "工时费优惠不能为空", trigger: "blur" }
        ],
        materialDiscountMoney: [
          { required: true, message: "原料费优惠不能为空", trigger: "blur" }
        ],
        settlementTime: [
          { required: true, message: "结算时间不能为空", trigger: "blur" }
        ],
        paymentMethod: [
          { required: true, message: "支付方式不能为空", trigger: "blur" }
        ],
        paymentAccount: [
          { required: true, message: "付款账号不能为空", trigger: "blur" }
        ],
        paymentAccountName: [
          { required: true, message: "账号名称不能为空", trigger: "blur" }
        ],
        paymentVoucher: [
          { required: true, message: "付款凭证不能为空", trigger: "blur" }
        ],
      },
    };
  },
  created() {
    this.form = {...this.$route.params}
    this.form.createBy = this.$store.state.user.userInfo.userName
    this.form.createTime = formatDate(new Date().getTime())
    this.getClientList();
  },
  methods: {
    /** 客户列表 */
    getClientList() {
      listClient().then(res =>{
        this.clientOpt = res.rows
        if (this.clientOpt.length > 0) {
          let client = this.clientOpt.find(item => item.id === this.form.clientId)
          // this.form.clientId = client.id
          this.form.clientType = client.type
          this.form.clientName = client.name
          this.form.clientPhone = client.phone
          this.form.clientCertificateType = client.certificateType
          this.form.clientCertificateNumber = client.certificateNumber
        }
      })
    },
    // 取消按钮
    cancel() {
      this.$tab.closeOpenPage({path: '/settlement/settlementMaintain?clientType=1'})
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        clientId: undefined,
        clientName: undefined,
        clientPhone: undefined,
        clientType: undefined,
        clientCertificateType: undefined,
        clientCertificateNumber: undefined,
        totalActualTimeMoney: 0,
        totalMaterialMoney: 0,
        totalTrailerMoney: 0,
        totalMoney: 0,
        receivableMoney: 0,
        practicalMoney: 0,
        settlementNumber: undefined,
        settlementTime: undefined,
        manHourDiscountMoney: 0,
        materialDiscountMoney: 0,
        paymentMethod: undefined,
        paymentVoucher: undefined,
        settlementRemark: undefined,
      };
      this.resetForm("form");
    },
    // 工时费或原料费优惠金额更改
    moneyChange() {
      this.form.practicalMoney = this.form.receivableMoney - this.form.manHourDiscountMoney - this.form.materialDiscountMoney
    },
    // 结算明细删除
    handleRowDelete(row) {
      this.settlementRepairFormList = this.settlementRepairFormList.filter(item => item.id !== row.id);
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.open1 = true
      this.title = '报修单详情'
      this.repairFormId = row.id
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getRepairForm(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改报修单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.form.repairFormIds = this.form.settlementRepairFormList.map(item => item.id)
          addSettlementMaintain(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          }).catch(() =>{
            this.buttonLoading = false;
          }).finally(() => {
            this.buttonLoading = false;
            this.$tab.closeOpenPage({path: '/settlement/settlementMaintain?clientType=1'})
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除报修单编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delSettlementMaintain(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/repairForm/settlement/export', {
        ...this.queryParams
      }, `待结算报修单_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped lang="scss">
.footer-container {
  position: fixed;
  bottom: 0;
  right: 0;
  width: 100%;
  padding: 16px;
  text-align: right;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}
</style>
