<template>
  <div ref="list">
    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch" label-width="95px" >
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="客户" prop="userId">-->
<!--        <el-select v-model="queryParams.userId" placeholder="请选择客户" clearable>-->
<!--          <el-option-->
<!--            v-for="item in lsUser"-->
<!--            :key="item.userId"-->
<!--            :label="item.userName"-->
<!--            :value="item.userId"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="代理商" prop="brokerId">-->
<!--        <el-input-->
<!--          v-model="queryParams.brokerId"-->
<!--          placeholder="请输入代理商"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="提交时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 200px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
<!--      <el-form-item label="提交时间" prop="submitTime">-->
<!--        <el-date-picker clearable-->
<!--                        style="width: 100%"-->
<!--                        v-model="dateRange"-->
<!--                        type="date"-->
<!--                        value-format="yyyy-MM-dd"-->
<!--                        placeholder="请选择提交时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="放款利率" prop="loanRate">-->
<!--        <el-input-->
<!--          v-model="queryParams.loanRate"-->
<!--          placeholder="请输入放款利率"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="贷款期限" prop="loadMonth">-->
<!--        <el-input-->
<!--          v-model="queryParams.loadMonth"-->
<!--          placeholder="请输入贷款期限"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="是否首贷" prop="isFirst">-->
<!--        <el-select v-model="queryParams.isFirst" placeholder="请选择是否首贷" clearable>-->
<!--          <el-option-->
<!--            v-for="dict in lsIsFirst"-->
<!--            :key="dict.id"-->
<!--            :label="dict.name"-->
<!--            :value="dict.id"-->
<!--            @keyup.enter.native="handleQuery"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="状态" prop="staus">
        <el-select v-model="queryParams.staus" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in lsStatus"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
            @keyup.enter.native="handleQuery"
          />
        </el-select>
        <!--        <el-input-->
        <!--          v-model="queryParams.staus"-->
        <!--          placeholder="请输入状态"-->
        <!--          clearable-->
        <!--          @keyup.enter.native="handleQuery"-->
        <!--        />-->
      </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"-->
<!--          v-hasPermi="['order:order:add']"-->
<!--        >新增-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['order:order:edit']"-->
<!--        >修改-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['order:order:remove']"-->
<!--        >删除-->
<!--        </el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['order:order:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="orderList" @sort-change="handleSortChange" :height="tableHeight - 150"
              @selection-change="handleSelectionChange" row-key="id"
             >
      <el-table-column type="selection" width="55" align="center"/>
      <!--              <el-table-column label="id" align="center" prop="id" sortable='custom' />-->
      <el-table-column label="订单号" align="center" prop="orderNo" sortable='custom' width="90px"/>
      <el-table-column label="客户" align="center" prop="userName" />
      <el-table-column label="代理商" align="center" prop="brokerName"   width="90px"/>
      <el-table-column label="产品名称" align="center" prop="productName" sortable='custom'  width="100px"/>
      <el-table-column label="提交时间" align="center" prop="submitTime" width="180" sortable='custom' >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.submitTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请额" align="center" prop="applyAmount" sortable='custom'  width="90px"/>
      <el-table-column label="授信额" align="center" prop="limitAmount" sortable='custom' width="90px"/>
      <el-table-column label="放款额" align="center" prop="loanAmount" sortable='custom' width="90px"/>
      <el-table-column label="放款利率" align="center" prop="loanRate" sortable='custom' width="100px"/>
      <el-table-column label="贷款期限" align="center" prop="loadMonth" sortable='custom'  width="100px"/>
      <el-table-column label="首贷" align="center" prop="isFirst" sortable='custom'/>
      <el-table-column label="可结算金额" align="center" prop="settleAmount" sortable='custom'  width="120px"/>
      <el-table-column label="状态" align="center" prop="staus" sortable='custom'>
        <template slot-scope="scope">
          <el-tag v-if="scope.row.staus == '0'" type="warning">未完成</el-tag>
          <el-tag v-if="scope.row.staus == '1'" type="success">已完成</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" sortable='custom'/>
    </el-table>

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

    <!-- 添加或修改代理商经纪对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单号" prop="orderNo">
              <BillNumberInput v-model="form.orderNo" title="订单编号"></BillNumberInput>
              <!--              <el-input v-model="form.orderNo" placeholder="请输入订单号"/>-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户" prop="userId">
              <el-select style="width: 100%;"  v-model="form.userId" placeholder="请选择客户" clearable>
                <el-option v-for="info in lsUser" :key="info.userId" :label="info.userName"
                           :value="info.userId"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="代理商" prop="brokerId">
              <treeselect v-model="form.brokerId" :options="brokerOptions" props="lable" :show-count="true" :defaultExpandLevel="Infinity"
                          placeholder="选择上级代理商" :normalizer="tenantIdnormalizer" />
              <!--              <el-input v-model="form.brokerId" placeholder="请输入代理商"/>-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品" prop="productId">
              <el-select style="width: 100%;"  v-model="form.productId" placeholder="请选择产品" clearable>
                <el-option v-for="info in lsProduct" :key="info.id" :label="info.productName"
                           :value="info.id"/>
              </el-select>
              <!--              <el-input v-model="form.productId" placeholder="请输入产品id"/>-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!--                <el-col :span="12">-->
          <!--                  <el-form-item label="产品名称" prop="productName">-->
          <!--                    <el-input v-model="form.productName" placeholder="请输入产品名称" />-->
          <!--                  </el-form-item>-->
          <!--                </el-col>-->
          <el-col :span="12">
            <el-form-item label="提交时间" prop="submitTime">
              <el-date-picker clearable
                              style="width: 100%"
                              v-model="form.submitTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择提交时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请额(万元)" prop="applyAmount">
              <el-input-number v-model="form.applyAmount" placeholder="请输入申请额" :min="0" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="授信额(万元)" prop="limitAmount">
              <el-input-number v-model="form.limitAmount" placeholder="请输入授信额" :min="0" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="放款额(万元)" prop="loanAmount">
              <el-input-number v-model="form.loanAmount" placeholder="请输入放款额" :min="0" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="放款利率" prop="loanRate">
              <el-input-number v-model="form.loanRate" placeholder="请输入放款利率" :min="0" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="贷款期限(月)" prop="loadMonth">
              <el-input-number v-model="form.loadMonth" placeholder="请输入贷款期限" :min="0" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否首贷" prop="isFirst">
              <el-select style="width: 100%;"  v-model="form.isFirst" placeholder="请选择是否首贷" clearable>
                <el-option v-for="info in lsIsFirst" :key="info.id" :label="info.name"
                           :value="info.id"/>
              </el-select>
              <!--              <el-input v-model="form.isFirst" placeholder="请输入是否首贷"/>-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="可结算金额（万元）" prop="settleAmount">
              <el-input-number v-model="form.settleAmount" placeholder="请输入可结算金额" :min="0" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="staus">
              <el-select style="width: 100%;"  v-model="form.staus" placeholder="请选择状态" clearable>
                <el-option v-for="info in lsStatus" :key="info.id" :label="info.name"
                           :value="info.id"/>
              </el-select>
              <!--              <el-input v-model="form.staus" placeholder="请输入状态"/>-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {pageListOrder, getOrder, delOrder, addOrder, updateOrder} from "@/api/order/order";
import {
  listUserByType,
} from "@/api/system/user";
import {
  listBrokerByTree
} from "@/api/broker/broker";
import {pageListInfo, getInfo, delInfo, addInfo, updateInfo,changeStatus,listInfo} from "@/api/product/info";
import AutoTableHeight from '@/views/broker/AutoTableHeight';
import {changeUserStatus} from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "DfOrder",
  mixins: [AutoTableHeight],
  dicts: ["df_broker_staus","sys_yes_no"],
  components: {Treeselect},
  props: {
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      // 日期范围
      dateRange: [],
      userId: "",
      rowDataNew: {},
      lsStatus: [
        {id: '0', name: "未完成"},
        {id: '1', name: "已完成"},
      ],
      lsIsFirst: [
        {id: '1', name: "是"},
        {id: '0', name: "否"}
      ],
      lsProduct: [],
      brokerOptions: [],
      lsUser: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中名字
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户订单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: null,
        userId: null,
        brokerId: null,
        productId: null,
        productName: null,
        submitTime: null,
        applyAmount: null,
        limitAmount: null,
        loanAmount: null,
        loanRate: null,
        loadMonth: null,
        isFirst: null,
        settleAmount: null,
        staus: null,
        submitTimeBegin: null,
        submitTimeEnd: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderNo: [
          {required: true, message: "订单号不能为空", trigger: "blur"}
        ],
        userId: [
          {required: true, message: "客户不能为空", trigger: "blur"}
        ],
        brokerId: [
          {required: true, message: "代理商不能为空", trigger: "blur"}
        ],
        productId: [
          {required: true, message: "产品不能为空", trigger: "blur"}
        ],
        // productName: [
        //   {required: true, message: "产品名称不能为空", trigger: "blur"}
        // ],
        submitTime: [
          {required: true, message: "提交时间不能为空", trigger: "blur"}
        ],
        staus: [
          {required: true, message: "状态不能为空", trigger: "blur"}
        ],
      }
    };
  },
  mounted() {
    // 初始化时将 rowData 的值赋给 row
    this.rowDataNew = this.rowData;
  },
  watch: {
    // 监听 rowData 的变化
    rowData: function (newVal, oldVal) {
      // 当 rowData 变化时更新 row 的值并打印
      this.rowDataNew = newVal;
      this.userId = this.rowDataNew.userId;
      // const allIds = this.getAllIds(this.rowDataNew);
      this.queryParams.userId = this.rowDataNew.userId;
      this.getList();
    },
  },
  created() {
    this.getList();
    this.getUser();
    this.getBroker();
    this.getProuct();
  },
  methods: {
    getProuct() {
      listInfo().then(response => {
        this.lsProduct = response.data;
      });
    },
    tenantIdnormalizer(node, instanceId) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.brokerName,
        children: node.children
      }
    },
    getBroker() {
      listBrokerByTree().then(response => {
        this.brokerOptions = response.data;
      });
    },
    getUser() {
      var params = {
        userType: "kh",
        selectAll: "1"
      }
      listUserByType(params).then(response => {
        this.lsUser = response.rows;
      });
    },
    /** 查询客户订单列表 */
    getList() {
      this.loading = true;
      this.queryParams.submitTimeBegin = this.dateRange[0];
      this.queryParams.submitTimeEnd = this.dateRange[1];
      pageListOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(e => {
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderNo: null,
        userId: null,
        brokerId: null,
        productId: null,
        productName: null,
        submitTime: null,
        applyAmount: null,
        limitAmount: null,
        loanAmount: null,
        loanRate: null,
        loadMonth: null,
        isFirst: null,
        settleAmount: null,
        staus: null,
        remark: null,
      };
      this.resetForm("form");
    },
    //排序
    handleSortChange(col) {
      this.$sortBy(col, this.queryParams);
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.names = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.submitTime = new Date();
      this.form.staus = '0';
      this.title = "添加客户订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getOrder(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客户订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      var productId = this.form.productId;
      var product = this.lsProduct.find(function(item) {
        return item.id === productId;
      });
      this.form.productName = product ? product.productName : null;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names = row.id || this.names;
      this.$modal.confirm('是否确认删除客户订单为"' + names + '"的数据项？').then(function () {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('order/order/export', {
        ...this.queryParams
      }, `客户订单_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
