<template>
  <div class="app-container new-box">
    <el-card>
      <!-- 搜索工作栏 -->
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <div class="filter-box">
          <div class="filter-lf">
            <el-form-item label="申请类型" prop="billType">
              <el-select v-model="queryParams.billType" placeholder="请选择申请类型" clearable size="small">
                <el-option v-for="dict in applyTypeList" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.BS_EXPENSE_APPLY_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="行程" prop="remark">
              <AreaTree v-model="queryParams.remark" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <!-- 操作工具栏 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-dropdown trigger="click" v-hasPermi="['bs:expense-apply:create']" @command="handleCommand">
            <el-button type="primary" size="mini" style="margin-right:5px;">
              <i class="el-icon-plus"></i> 创建申请单
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="beforeHandleCommand(1)">
                <el-button type="text">出差申请单</el-button>
              </el-dropdown-item>
              <el-dropdown-item :command="beforeHandleCommand(2)">
                <el-button type="text">日常申请单</el-button>
              </el-dropdown-item>

            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading" v-hasPermi="['bs:expense-apply:export']">导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 列表 -->
      <el-table stripe border :data="list" v-loading="loading">
        <el-table-column label="申请单号" align="center" prop="applyNo" />
        <el-table-column label="项目名称" align="center" prop="projectName" />
        <el-table-column label="申请人" align="center" prop="nickname" />
        <el-table-column label="申请类型" align="center" prop="billType">
          <template v-slot="scope">
            <dict-tag :type="DICT_TYPE.BS_BILL_TYPE" :value="scope.row.billType" />
          </template>
        </el-table-column>
        <el-table-column label="行程路线" align="center" prop="rode">
          <template slot-scope="scope">
            {{scope.row.rode || '-'}}
          </template>
        </el-table-column>
        <el-table-column label="出差天数" align="center" prop="tripDay">
          <template slot-scope="scope">
            {{scope.row.tripDay? `${scope.row.tripDay}天` : '-'}}
          </template>
        </el-table-column>
        <el-table-column label="开始-结束时间" align="center" prop="time" />
        <el-table-column label="审批状态" align="center" prop="status">
          <template v-slot="scope">
            <dict-tag :type="DICT_TYPE.BS_EXPENSE_APPLY_STATUS" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template v-slot="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" :disabled="scope.row.status!=0" @click="handleUpdate(scope.row)" v-hasPermi="['bs:expense-apply:create']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleShow(scope.row)" v-hasPermi="['bs:expense-apply:show']">查看</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" :disabled="scope.row.status!=0" @click="handleDelete(scope.row)" v-hasPermi="['bs:expense-apply:delete']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script>
import { updateExpenseApply, deleteExpenseApply, getExpenseApply, getExpenseApplyPage, exportExpenseApplyExcel } from "@/api/bs/expenseApply";
import { findAreaIdName } from '@/utils';
import dayjs from 'dayjs';
export default {
  name: "ExpenseApply",
  components: {
    AreaTree: () => import('@/components/AreaTree')
  },
  created() {
    this.applyTypeList = this.getDictDatas(this.DICT_TYPE.BS_BILL_TYPE).filter(item => !["CLBX", "RCBX"].includes(item.value))
    this.getList();
  },
  activated() {
    this.getList();
  },

  data() {
    return {
      billType: '',
      applyTypeList: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 申请单列表
      list: [],
      // 查询参数
      queryParams: {
        destinationLocation: null,
        pageNo: 1,
        pageSize: 10,
        billType: null,
        applyNo: null,
        userId: null,
        nickname: null,
        deptId: null,
        deptName: null,
        projectName: null,
        reason: null,
        amount: null,
        status: null,
        remark: null,
        files: null,
        createBy: null,
        createTime: [],
        updateBy: null,
        // sortingFields: { order: "desc" }
      },
    };
  },
  methods: {
    handleCommand(val) {
      const { index, row } = val
      //  1 出差 2 报销 3 日常
      if (index === 1) {
        this.$router.push({ path: "/bs/expenseApply/business", query: { id: null, flag: 'add', title: '出差申请单添加', typeStr: 'business' } });
      } else {
        this.$router.push({ path: "/bs/expenseApply/business", query: { id: null, flag: 'add', title: '日常申请单添加', typeStr: 'daily' } });
      }
    },
    beforeHandleCommand(index, data) {
      return {
        'index': index,
        'row': data
      }
    },
    unique(arr) {
      let newArr = [arr[0]]

      for (let i = 1; i < arr.length; i++) {

        if (arr[i] !== newArr[newArr.length - 1]) {

          newArr.push(arr[i])

        }

      }
      return newArr
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      console.log(this.queryParams)
      // 执行查询
      getExpenseApplyPage(this.queryParams).then(response => {
        this.list = response.data.list || [];
        this.total = response.data.total
        let areaList = this.$store.getters.areaTree
        this.list = this.list.map((item) => {
          return {
            ...item,
            amount: (item.expenseApplyTrips || []).reduce((acc, cur) => {
              return Number(acc) + Number(cur.amount)
            }, 0),
            tripDay: (item.expenseApplyTrips || []).reduce((acc, cur) => {
              return Number(acc) + Number(cur.tripDay)
            }, 0),
            rodeArr: ((item.expenseApplyTrips || []).map(item => {
              return [(findAreaIdName(areaList, item.departureLocation) || {}).name, (findAreaIdName(areaList, item.destinationLocation) || {}).name]
            })),
            time: Array.isArray(item.expenseApplyTrips) && item.expenseApplyTrips.length ? `${dayjs(item.expenseApplyTrips[0].startTime).format('YYYY/MM/DD')}~${dayjs(item.expenseApplyTrips[item.expenseApplyTrips.length - 1].endTime).format('YYYY/MM/DD')}` : '-'
          }
        })
        this.list.forEach(element => {
          let arr = []
          element.rodeArr.forEach(v => {
            v.forEach(n => {
              arr.push(n && n)
            })
          })
          element.rodeArr = arr
        });

        //去重
        this.list.forEach(n => {
          n.rode = this.unique(n.rodeArr).join('-')
        })

        this.billType = this.list.length ? this.list[0].billType : null
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        billType: undefined,
        applyNo: undefined,
        userId: undefined,
        nickname: undefined,
        deptId: undefined,
        deptName: undefined,
        projectName: undefined,
        reason: undefined,
        amount: undefined,
        status: undefined,
        remark: undefined,
        files: undefined,
        createBy: undefined,
        updateBy: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const { billType } = row
      if (billType === 'CLSQ') {
        this.$router.push({ path: "/bs/expenseApply/business", query: { id: row.id, flag: 'edit', title: '出差申请单修改', typeStr: 'business' } });
      } else if (billType === 'RCSQ') {
        this.$router.push({ path: "/bs/expenseApply/business", query: { id: row.id, flag: 'edit', title: '日常申请单修改', typeStr: 'daily' } });
      }
    },
    // 查看按钮
    handleShow(row) {
      const { billType } = row
      if (billType === 'CLSQ') {
        this.$router.push({ path: "/bs/expenseApply/business", query: { id: row.id, flag: 'show', title: '出差申请单查看', typeStr: 'business' } });
      } else if (billType === 'RCSQ') {
        this.$router.push({ path: "/bs/expenseApply/business", query: { id: row.id, flag: 'show', title: '日常申请单查看', typeStr: 'daily' } });
      }
    },
    /** 提交按钮 */
    submitForm(type) {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          let newForm = {
            ...this.form,
            status: type,
          }
          updateExpenseApply(newForm).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        console.log('form', this.form);
        // createExpenseApply(this.form).then(response => {
        //   this.$modal.msgSuccess("新增成功");
        // });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除申请单编号为"' + id + '"的数据项?').then(function () {
        return deleteExpenseApply(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = { ...this.queryParams };
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有申请单数据项?').then(() => {
        this.exportLoading = true;
        return exportExpenseApplyExcel(params);
      }).then(response => {
        this.$download.excel(response, '申请单.xls');
        this.exportLoading = false;
      }).catch(() => { });
    }
  }
};
</script>

<style lang='scss' scoped>
@import '@/assets/styles/header/index.scss';
@import '@/assets/styles/common/index.scss';
</style>
