<template>
  <section class="custom-page">
    <h2>农机租赁管理</h2>
    <br />
    <avue-crud
      ref="crudRef"
      v-model:search="searchCondition"
      v-model:page="pageData"
      :data="data"
      :option="option"
      :table-loading="_loading"
      :before-close="handleDialogClose"
      @search-change="
        (form, done) => {
          getData(1);
          done();
        }
      "
      @search-reset="() => getData(1)"
      @current-change="getData"
      @size-change="getData"
      @row-save="handleRowSave"
    >
      <template #menu="{ row }">
        <el-button type="primary" @click="handleView(row)">详情</el-button>
      </template>
      <template #certiUrl-form="{ type }">
        <Attrs v-model:attrs="certiAttrs" :type="type" :file-num="2" />
      </template>
      <template #contractUrl-form="{ type }">
        <Attrs v-model:attrs="contractAttrs" :type="type" :file-num="2" />
      </template>
    </avue-crud>
  </section>
</template>

<script setup>
import { ref, reactive, onMounted, h } from 'vue';
import { CRUD_OPTIONS, customRules } from '@/config';
import Attrs from '../common/Attrs.vue';
import inputSuppliesApi from '@/apis/inputSuppliesApi';
import { ElMessage } from 'element-plus';

onMounted(getData);

/* --------------- data --------------- */
// #region
const crudRef = ref();
const _loading = ref(false);
const searchCondition = ref({
  tenant: '',
});
const pageData = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});
const data = ref([]);
const option = reactive({
  ...CRUD_OPTIONS,
  selection: false,
  refreshBtn: false,
  dialogWidth: '50%',
  column: [
    {
      hide: true,
      search: true,
      label: '关键字',
      prop: 'tenant',
      addDisplay: false,
      viewDisplay: false,
    },
    {
      label: '承租方',
      prop: 'tenant',
      rules: customRules({ msg: '请输入承租方姓名' }),
    },
    {
      hide: true,
      label: '出租方',
      prop: 'lessor',
      rules: customRules({ msg: '请输入出租方姓名' }),
    },
    {
      label: '承租方联系方式',
      prop: 'tenantPhone',
      rules: customRules({ msg: '请输入承租方联系方式' }),
    },
    {
      hide: true,
      label: '出租方联系方式',
      prop: 'lessorPhone',
      rules: customRules({ msg: '请输入出租方联系方式' }),
    },
    {
      label: '租赁设备',
      prop: 'leaseEquipment',
      rules: customRules({ msg: '请输入租赁设备' }),
    },
    {
      label: '租赁数量',
      prop: 'leaseNumber',
      type: 'number',
      min: 1,
      step: 1,
      stepStrictly: true,
      suffix: '台',
      viewDisplay: false,
      rules: customRules({ msg: '请输入租赁数量' }),
      render: ({ row }) => `${row.leaseNumber}台`,
    },
    {
      hide: true,
      label: '租赁数量',
      prop: 'leaseNumber1',
      addDisplay: false,
      // renderForm: ({ row }) => h('span', {}, `${row.leaseNumber}台`),
    },
    {
      hide: true,
      label: '支付方式',
      prop: 'payMethod',
      rules: customRules({ msg: '请选择支付方式' }),
    },
    {
      label: '租赁期限',
      prop: 'term',
      addDisplay: false,
    },
    {
      hide: true,
      label: '租金',
      prop: 'rent',
      type: 'number',
      min: 1,
      step: 0.01,
      precision: 2,
      stepStrictly: true,
      suffix: '元/天/台',
      rules: customRules({ msg: '请输入租赁价格' }),
    },
    {
      label: '合同金额',
      prop: 'allMoney',
      addDisplay: false,
      rules: customRules({ msg: '请输入合同金额' }),
    },
    {
      hide: true,
      label: '起止时间',
      prop: 'startEndTime',
      type: 'datetimerange',
      format: 'YYYY-MM-DD HH:mm',
      valueFormat: 'YYYY-MM-DD HH:mm',
      startPlaceholder: '开始时间',
      endPlaceholder: '终止时间',
      span: 24,
      rules: customRules({ msg: '请选择起止时间' }),
    },
    {
      hide: true,
      label: '机械合格证',
      prop: 'certiUrl',
    },
    {
      hide: true,
      label: '租赁合同',
      prop: 'contractUrl',
    },
  ],
});
const certiAttrs = ref([]);
const contractAttrs = ref([]);

// #endregion

/* --------------- methods --------------- */
// #region

function handleDialogClose(done) {
  certiAttrs.value = [];
  contractAttrs.value = [];
  done();
}
async function getData(resetPage) {
  resetPage === 1 && (pageData.value.currentPage = 1);
  _loading.value = true;
  let params = Object.assign(
    {
      current: pageData.value.currentPage,
      size: pageData.value.pageSize,
    },
    searchCondition.value
  );
  let res = await inputSuppliesApi.getLeaseSuperviseList(params);
  _loading.value = false;
  if (res.code == 200) {
    data.value = res.data.records.map((v) => {
      let d = leaseDate(v.startEndTime);
      let obj = {
        ...v,
        leaseNumber1: v.leaseNumber + '台',
        term: d + '天',
        allMoney: (v.rent * v.leaseNumber * d).toFixed(2) + '元',
      };
      return obj;
    });
    pageData.value.total = res.data.total;
  }
}

async function handleRowSave(form, done, loading) {
  let data = Object.assign({}, form);
  delete data.allMoney;
  if (certiAttrs.value.length) {
    data.certiUrl = certiAttrs.value.map((v) => v.url).join();
  }
  if (contractAttrs.value.length) {
    data.contractUrl = contractAttrs.value.map((v) => v.url).join();
  }
  data.startEndTime = data.startEndTime.join();
  let res = await inputSuppliesApi.addLeaseSupervise(data);
  loading();
  if (res.code == 200) {
    getData();
    ElMessage.success('租赁信息添加成功');
    // done();
  }
}
function handleView(row) {
  if (row.certiUrl) {
    certiAttrs.value = row.certiUrl.split(',').map((v, i) => {
      return {
        url: v,
        uid: `certi_${i}_${Date.now()}`,
      };
    });
  }
  if (row.contractUrl) {
    contractAttrs.value = row.contractUrl.split(',').map((v, i) => {
      return {
        url: v,
        uid: `contract_${i}_${Date.now()}`,
      };
    });
  }
  crudRef.value.rowView(row);
}
function leaseDate(date) {
  let n = 0;
  if (date) {
    let arr = date.split(',');
    let a1 = new Date(arr[0]).getTime();
    let a2 = new Date(arr[1]).getTime();
    n = Math.ceil((a2 - a1) / (1000 * 60 * 60 * 24));
  }
  return n;
}
// #endregion
</script>

<style lang="scss" scoped></style>
