<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="合同名称" prop="contractName">
        <el-input v-model="queryParams.contractName" placeholder="请输入合同名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="合同编号" prop="contractNo">
        <el-input v-model="queryParams.contractNo" placeholder="请输入合同编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="供方" prop="supplier">
        <el-input v-model="queryParams.supplier" placeholder="请输入供方" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="需方" prop="customer">
        <el-input v-model="queryParams.customer" placeholder="请输入需方" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="签订时间" prop="signTime">
        <el-date-picker clearable v-model="queryParams.signTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择签订时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="签订地点" prop="signLocation">
        <el-input v-model="queryParams.signLocation" placeholder="请输入签订地点" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="合同状态" prop="contractStatus">
        <el-select v-model="queryParams.contractStatus" placeholder="请选择合同状态">
          <el-option label="草稿" value="0" />
          <el-option label="已生效" value="1" />
          <el-option label="已作废" value="2" />
          <el-option label="已完成" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
          @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
          @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange"
      @row-click="handleRowClick">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="合同名称" align="center" prop="contractName" />
      <el-table-column label="合同编号" align="center" prop="contractNo" />
      <el-table-column label="供方" align="center" prop="supplier" />
      <el-table-column label="需方" align="center" prop="customer" />
      <el-table-column label="签订时间" align="center" prop="signTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.signTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签订地点" align="center" prop="signLocation" />
      <el-table-column label="合同状态" align="center" prop="status">
        <template slot-scope="scope">
          <span-tag
            :type="scope.row.status == 0 ? 'info' : scope.row.status == 1 ? 'success' : scope.row.status == 2 ? 'danger' : 'primary'">
            {{ scope.row.status == 0 ? '草稿' : scope.row.status == 1 ? '已生效' : scope.row.status == 2 ? '已作废' : '已完成' }}
          </span-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click.stop="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click.stop="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改合同信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 前四个字段占一排 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="form.contractName" placeholder="请输入合同名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="合同编号" prop="contractNo">
              <el-input v-model="form.contractNo" placeholder="请输入合同编号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="签订时间" prop="signTime">
              <el-date-picker clearable v-model="form.signTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择签订时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="签订地点" prop="signLocation">
              <el-input v-model="form.signLocation" placeholder="请输入签订地点" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="产品内容">
          <editor v-model="form.productContent" :min-height="192" />
        </el-form-item>
        <el-form-item label="合同内容">
          <editor v-model="form.contractContent" :min-height="192" />
        </el-form-item>

        <!-- 供方和需方左右布局 -->
        <el-row :gutter="20">
          <!-- 供方信息 -->
          <el-col :span="12">
            <el-form-item label="供方" prop="supplier">
              <el-input v-model="form.supplier" placeholder="请输入供方" />
            </el-form-item>
            <el-form-item label="供方地址" prop="supplierAddress">
              <el-input v-model="form.supplierAddress" placeholder="请输入供方地址" />
            </el-form-item>
            <el-form-item label="供方电话" prop="supplierPhone">
              <el-input v-model="form.supplierPhone" placeholder="请输入供方电话" />
            </el-form-item>
            <el-form-item label="供方开户行" prop="supplierBank">
              <el-input v-model="form.supplierBank" placeholder="请输入供方开户行" />
            </el-form-item>
            <el-form-item label="供方账号" prop="supplierAccount">
              <el-input v-model="form.supplierAccount" placeholder="请输入供方账号" />
            </el-form-item>
            <el-form-item label="供方税号" prop="supplierTaxNo">
              <el-input v-model="form.supplierTaxNo" placeholder="请输入供方税号" />
            </el-form-item>
          </el-col>

          <!-- 需方信息 -->
          <el-col :span="12">
            <el-form-item label="需方" prop="customer">
              <el-input v-model="form.customer" placeholder="请输入需方" />
            </el-form-item>
            <el-form-item label="需方地址" prop="customerAddress">
              <el-input v-model="form.customerAddress" placeholder="请输入需方地址" />
            </el-form-item>
            <el-form-item label="需方电话" prop="customerPhone">
              <el-input v-model="form.customerPhone" placeholder="请输入需方电话" />
            </el-form-item>
            <el-form-item label="需方开户行" prop="customerBank">
              <el-input v-model="form.customerBank" placeholder="请输入需方开户行" />
            </el-form-item>
            <el-form-item label="需方账号" prop="customerAccount">
              <el-input v-model="form.customerAccount" placeholder="请输入需方账号" />
            </el-form-item>
            <el-form-item label="需方税号" prop="customerTaxNo">
              <el-input v-model="form.customerTaxNo" placeholder="请输入需方税号" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 最下方的附件和备注等信息保持原样 -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="技术附件" prop="techAnnex">
          <file-upload v-model="form.techAnnex"></file-upload>
        </el-form-item>
        <el-form-item label="商务附件" prop="businessAnnex">
          <file-upload v-model="form.businessAnnex"></file-upload>
        </el-form-item>
        <el-form-item label="排产函" prop="productionSchedule">
          <file-upload v-model="form.productionSchedule"></file-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="合同详情" :visible.sync="dialogOpen" fullscreen>
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="合同信息" name="first">
          合同信息
        </el-tab-pane>
        <el-tab-pane label="下发订单" name="second">
          <OrderPage v-if="activeTab === 'second'" :contractId="form.contractId" />
        </el-tab-pane>
        <el-tab-pane label="收款记录" name="third">
          <KLPTable v-loading="loading" :data="financeList">
            <el-table-column label="应收ID" align="center" prop="receivableId" v-if="false" />
            <!-- <el-table-column label="客户" align="center" prop="customerName" /> -->
            <el-table-column label="收款日期" align="center" prop="dueDate" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.dueDate, '{y}-{m}-{d}') }}</span>
                <!-- <el-tag v-if="new Date(scope.row.dueDate) < new Date()" type="danger">过期</el-tag>
          <el-tag v-else-if="new Date(scope.row.dueDate) > new Date()" type="success">还剩{{ parseInt((new Date(scope.row.dueDate) - new Date()) / (1000 * 60 * 60 * 24)) }}天</el-tag> -->
              </template>
            </el-table-column>
            <el-table-column label="收款金额" align="center" prop="amount" />
            <!-- <el-table-column label="已收金额" align="center" prop="paidAmount" /> -->
            <!-- <el-table-column label="未收金额" align="center" prop="balanceAmount" /> -->
            <!-- <el-table-column label="状态" align="center" prop="status" /> -->
            <el-table-column label="备注" align="center" prop="remark" />
          </KLPTable>
        </el-tab-pane>
        <el-tab-pane label="订单异议" name="fourth">
          <el-table v-loading="loading" :data="objectionList">
            <el-table-column label="编号" align="center" prop="objectionCode" />
            <el-table-column label="状态" align="center" prop="objectionStatus">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.objectionStatus === 0" type="danger">待处理</el-tag>
                <el-tag v-else-if="scope.row.objectionStatus === 1" type="success">已处理</el-tag>
                <el-tag v-else-if="scope.row.objectionStatus === 2" type="info">已关闭</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="处理人" align="center" prop="handleUser" />
            <el-table-column label="处理时间" align="center" prop="handleTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.handleTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" />
            <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"></el-button>
                <el-button size="mini" type="text" icon="el-icon-check" @click="handleDo(scope.row)"
                  v-if="scope.row.objectionStatus == 0"></el-button>
                <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
                  v-if="scope.row.objectionStatus == 1"></el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"></el-button>
              </template>
            </el-table-column> -->
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="发货配卷" name="fifth">
          <CoilTable :data="coilList" />
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import { listContract, getContract, delContract, addContract, updateContract, listContractOrderObjection, listContractPackaging } from "@/api/crm/contract";
import OrderPage from "@/views/crm/order/index.vue";
import CoilTable from "../components/CoilTable.vue";

export default {
  name: "Contract",
  components: {
    OrderPage,
    CoilTable,
  },
  data() {
    return {
      // 活动tab
      activeTab: "first",
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同信息表格数据
      contractList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      dialogOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractName: undefined,
        contractNo: undefined,
        supplier: undefined,
        customer: undefined,
        signTime: undefined,
        signLocation: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        contractId: [
          { required: true, message: "合同主键ID不能为空", trigger: "blur" }
        ],
        contractName: [
          { required: true, message: "合同名称不能为空", trigger: "blur" }
        ],
        contractNo: [
          { required: true, message: "合同编号不能为空", trigger: "blur" }
        ],
        supplier: [
          { required: true, message: "供方不能为空", trigger: "blur" }
        ],
        customer: [
          { required: true, message: "需方不能为空", trigger: "blur" }
        ],
        signTime: [
          { required: true, message: "签订时间不能为空", trigger: "blur" }
        ],
        signLocation: [
          { required: true, message: "签订地点不能为空", trigger: "blur" }
        ],
        productContent: [
          { required: true, message: "产品内容不能为空", trigger: "blur" }
        ],
        contractContent: [
          { required: true, message: "合同内容不能为空", trigger: "blur" }
        ],
        supplierAddress: [
          { required: true, message: "供方地址不能为空", trigger: "blur" }
        ],
        supplierPhone: [
          { required: true, message: "供方电话不能为空", trigger: "blur" }
        ],
        supplierBank: [
          { required: true, message: "供方开户行不能为空", trigger: "blur" }
        ],
        supplierAccount: [
          { required: true, message: "供方账号不能为空", trigger: "blur" }
        ],
        supplierTaxNo: [
          { required: true, message: "供方税号不能为空", trigger: "blur" }
        ],
        customerAddress: [
          { required: true, message: "需方地址不能为空", trigger: "blur" }
        ],
        customerPhone: [
          { required: true, message: "需方电话不能为空", trigger: "blur" }
        ],
        customerBank: [
          { required: true, message: "需方开户行不能为空", trigger: "blur" }
        ],
        customerAccount: [
          { required: true, message: "需方账号不能为空", trigger: "blur" }
        ],
        customerTaxNo: [
          { required: true, message: "需方税号不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "合同状态不能为空", trigger: "change" }
        ],
        financeList: [],
        oobjectionList: [],
        coilList: [],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询合同信息列表 */
    getList() {
      this.loading = true;
      listContract(this.queryParams).then(response => {
        this.contractList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询合同配卷列表 */
    getCoilList() {
      listContractPackaging(this.form.contractId).then(response => {
        this.coilList = response.data || [];
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 行点击事件
    handleRowClick(row) {
      this.form = row;
      this.dialogOpen = true;
      this.getCoilList();
      listContractOrderObjection(row.contractId).then(response => {
        this.form.financeList = response.data.financeList || [];
        this.form.oobjectionList = response.data.oobjectionList || [];
      })
    },
    // 表单重置
    reset() {
      this.form = {
        contractId: undefined,
        contractName: undefined,
        contractNo: undefined,
        supplier: undefined,
        customer: undefined,
        signTime: undefined,
        signLocation: undefined,
        productContent: undefined,
        contractContent: undefined,
        supplierAddress: undefined,
        supplierPhone: undefined,
        supplierBank: undefined,
        supplierAccount: undefined,
        supplierTaxNo: undefined,
        customerAddress: undefined,
        customerPhone: undefined,
        customerBank: undefined,
        customerAccount: undefined,
        customerTaxNo: undefined,
        techAnnex: undefined,
        businessAnnex: undefined,
        productionSchedule: undefined,
        status: 0,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.contractId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加合同信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const contractId = row.contractId || this.ids
      getContract(contractId).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;
          if (this.form.contractId != null) {
            updateContract(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addContract(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const contractIds = row.contractId || this.ids;
      this.$modal.confirm('是否确认删除合同信息编号为"' + contractIds + '"的数据项？').then(() => {
        this.loading = true;
        return delContract(contractIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('crm/contract/export', {
        ...this.queryParams
      }, `contract_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
