<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="未提交" :name="SubmitState.WILL_SUBMIT"></el-tab-pane>
      <el-tab-pane label="已提交" :name="SubmitState.HAS_SUBMIT"></el-tab-pane>
    </el-tabs>
    <el-form :model="queryParams" ref="queryForm" :inline="true" size="small" @submit.native.prevent>
      <el-form-item prop="purchaseName" label="标题">
        <el-input v-model="queryParams.purchaseName" placeholder="请输入标题" style="width:230px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain 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" v-show="activeName === SubmitState.WILL_SUBMIT">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['official:purchase:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">

      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="purchaseList" @selection-change="handleSelectionChange">
      <el-table-column type="index" align="center" label="序号" min-width="30px"></el-table-column>
      <el-table-column label="标题" align="center" min-width="130px" prop="purchaseName" />
      <el-table-column label="预算项目" prop="budgetName" align="center"></el-table-column>
      <el-table-column label="采购费用" sortable align="center" prop="purchaseMoney">
        <template slot-scope="scope">
          {{ scope.row.purchaseMoney }}元
        </template>
      </el-table-column>
      <el-table-column label="实际使用金额" sortable align="center" prop="sjPurchaseMoney">
        <template slot-scope="scope">
          {{ scope.row.sjPurchaseMoney }}元
        </template>
      </el-table-column>
      <el-table-column label="期望日期" sortable align="center" prop="expectedDate"></el-table-column>
      <el-table-column label="申请部门" align="center" prop="deptName"></el-table-column>
      <el-table-column label="申请人" key="applyUser" align="center" prop="applyUser" v-if="isShow">
      </el-table-column>
      <el-table-column label="申请时间" sortable align="center" prop="applyTime" v-if="isShow"></el-table-column>
      <el-table-column label="当前任务名称" key="taskName" prop="state" min-width="80" align="center">
        <template slot-scope="scope">
          <el-tag :type="resolveState(scope.row.taskName)">{{ scope.row.taskName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="100" key="operate">
        <template slot-scope="scope">
          <el-button v-if="scope.row.tjzt == '0'" size="mini" type="text" icon="el-icon-s-promotion"
            @click="submitApply(scope.row)" v-hasPermi="['system:teacherLeave:edit']">提交申请
          </el-button>
          <el-button v-if="scope.row.tjzt == '1'" size="mini" type="text" icon="el-icon-view"
            @click="handleView(scope.row)" v-hasPermi="['system:teacherLeave:edit']">查看
          </el-button>
          <el-button v-if="scope.row.tjzt == '0'" size="mini" type="text" icon="el-icon-edit"
            @click="handleUpdate(scope.row)" v-hasPermi="['system:teacherLeave:edit']">修改
          </el-button>
          <el-button v-if="scope.row.tjzt == '0'" size="mini" type="text" icon="el-icon-delete"
            @click="handleDelete(scope.row)" v-hasPermi="['system:teacherLeave:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <ExPagination v-show="total > 0" :total="total" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum"
      @pagination="getList"></ExPagination>
    <!-- 新增或修改采购对话框 -->
    <el-dialog :title="title" :visible.sync="openForPur" width="1100px" @close="refreshValidate">
      <!-- <div> -->
      <el-form ref="formPur" :model="formPur" :disabled="formPurDisable" :rules="rules" label-width="130px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="标题" prop="purchaseName">
              <el-input v-model="formPur.purchaseName" placeholder="请输入采购申请标题" clearable style="width: 650px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="申请部门" prop="deptId">
              <Treeselect :disabled="formPurDisable" v-model="formPur.deptId" @select="deptIdAndName"
                :options="deptOptions" :show-count="true" placeholder="请选择归属部门" :defaultExpandLevel=1
                style="width: 208px" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="期望日期" prop="expectedDate">
              <el-date-picker v-model="formPur.expectedDate" placeholder="请选择期望日期" clearable value-format="yyyy-MM-dd"
                style="width: 208px"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="批复项目" prop="budgetId">
              <el-select v-model="formPur.budgetId" @change="getBudgetName" placeholder="请选择批复项目" style="width: 208px">
                <el-option v-for="item in budgetList" :key="item.id" :label="item.budgetName"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="可用余额（元）" prop="kyye">
              <el-input placeholder="请输入" v-model="formPur.kyye" readonly clearable style="width: 208px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="采购金额(元)" prop="purchaseMoney">
              <el-input :value="purchaseMoney" readonly clearable style="width: 208px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="实际使用金额(元)" prop="sjPurchaseMoney">
              <el-input v-model="formPur.sjPurchaseMoney" clearable style="width: 208px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="分管处室领导" prop="handUserName1">
              <el-input placeholder="请选择分管领导" v-model="formPur.handUserName1" clearable @click.native="selectBoss1(1)"
                style="width: 208px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="财务领导" prop="handUserName2">
              <el-input placeholder="请选择财务领导" v-model="formPur.handUserName2" clearable @click.native="selectBoss1(2)"
                style="width: 208px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item label="采购说明">
              <el-input type="textarea" v-model="formPur.remark" placeholder="请输入采购说明" clearable
                style="width: 208px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button v-if="isEdit" type="primary" size="mini" :disabled="add" @click="addRow">增加</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button v-if="isEdit" type="danger" :disabled="multiple" size="mini" @click="delRow">删除</el-button>
        </el-col>
      </el-row>
      <div style="height:10px"></div>
      <el-table :data="projectDetail" v-loading="loading" style="width: 100%"
        @selection-change="handleSelectionChangeDetail">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column type="index" label="序号" width="48"></el-table-column>
        <el-table-column prop="assetsTypeName" label="资产分类" align="center" width="120">
          <template slot-scope="scope">
            <span v-show="!isEdit">{{ scope.row.assetsTypeName }}</span>
            <el-input v-show="isEdit" v-model="scope.row.assetsTypeName"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="assetsName" label="资产名称" align="center" width="180px">
          <template slot-scope="{ row }">
            <span v-show="!isEdit">{{ row.assetsName }}</span>
            <el-input v-show="isEdit" v-model="row.assetsName"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="assetsSpecs" label="规格型号" align="center">
          <template slot-scope="{ row }">
            <span v-show="!isEdit">{{ row.assetsSpecs }}</span>
            <el-input v-show="isEdit" v-model="row.assetsSpecs"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="assetsUnit" label="单位" align="center" width="100px">
          <template slot-scope="{ row }">
            <span v-show="!isEdit">{{ row.assetsUnit }}</span>
            <el-input v-show="isEdit" v-model="row.assetsUnit"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="assetsPrice" label="单价-元" align="center" width="120px">
          <template slot-scope="{ row }">
            <span v-show="!isEdit">{{ row.assetsPrice }}</span>
            <el-input v-show="isEdit" v-model="row.assetsPrice" type="number"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="assetsNumbers" label="数量" align="center" width="110px">
          <template slot-scope="{ row }">
            <span v-show="!isEdit">{{ row.assetsNumbers }}</span>
            <el-input v-show="isEdit" v-model="row.assetsNumbers"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="totalPrice" label="小计" align="center" width="120px">
          <template slot-scope="{ row }">
            <span>{{ row.assetsPrice * row.assetsNumbers }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" align="center">
          <template slot-scope="{ row }">
            <span v-show="!isEdit">{{ row.remark }}</span>
            <el-input v-show="isEdit" v-model="row.remark"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <!-- </div> -->
      <div slot="footer">
        <!--        v-if="submit==1"-->
        <el-button v-if="!formPurDisable" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelPur">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 选择资产分类 -->
    <el-drawer ref="refDrawer" :title="title" :visible.sync="drawer">
      <Treeselect v-model="formPur.assetsType" @select="assetsIdAndName" :options="assetsOptions" :defaultExpandLevel=3
        :show-count="true" placeholder="请选择资产分类" />
    </el-drawer>

    <BossSelect v-if="teacherOptions.open" :openSelect.sync="teacherOptions.open" :title="teacherOptions.title"
      @getTeacherList="getTeacherList" @setTeacherInfo="setTeacherInfo"></BossSelect>
  </div>
</template>

<script>
import {
  purchaseList,
  getLeaderList,
  purchaseListByTitle,
  submitPurchaseList,
  addPurchaseList,
  delPurchaseList,
  getPurchaseListDetaial,
  editPurchaseList,
  getAssetsType,
  getDeptTree,
  getBudgetList1,
  teacherListInform
} from "@/api/smartSchool/officialWork/purchaseApply.js"
import { SubmitState } from "@/enums/apply";
import BossSelect from '@/views/components/moduleComponets/BossSelect/index.vue'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { deptTreeSelect } from "@/api/system/user";

export default {
  name: 'index',
  add: false,
  submit: '1',
  dialogDisable: "",
  components: { Treeselect, BossSelect },
  props: {},
  data() {
    return {
      // 选择领导人对话框
      teacherOptions: {
        open: false,
        title: '选择领导',
        token: null
      },


      formPurDisable: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        submitState: 0,
        purchaseName: null,
      },
      loading: true,
      purchaseList: [
        // {"id":223}
      ],

      // tab标签选中值
      activeName: SubmitState.WILL_SUBMIT,
      SubmitState,
      // 新增对话框
      openForPur: false,
      // 采购表单
      formPur: {},
      // 标题
      title: "",
      // 总条数
      total: 0,
      // 表单校验
      rules: {
        purchaseName: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        deptId: [{ required: true, message: '申请部门不能为空', trigger: 'change' }],
        budgetName: [{ required: true, message: '批复项目不能为空', trigger: 'blur' }],
        expectedDate: [{ required: true, message: '期望日期不能为空', trigger: 'blur' }],
        title: [{ required: true, message: '分管处室领导不能为空', trigger: 'blur' }],
        handUserName1: [{ required: true, message: '分管处室领导不能为空', trigger: 'change' }],
        handUserName2: [{ required: true, message: '财务领导不能为空', trigger: 'change' }],
        budgetId: [{ required: true, message: '批复项目不能为空', trigger: 'change' }],
      },
      // 项目预算详细
      projectDetail: [],
      // 项目详细创建索引
      createIndex: 0,
      // 项目预算详细选中数据
      id2s: [],
      // 非多个禁用
      multiple: true,
      //后端传校领导列表
      schoolLeaderList: [],
      // 部门树选项
      deptOptions: undefined,
      //后端传批复项目
      budgetList: [],
      // 控制表格是否可输入
      isEdit: false,
      // 后端传入的资产分类
      // assetsType:[],
      assetsOptions: [],
      // 抽屉对话框
      drawer: false,
      index: undefined,
      // 判断是否已提交页面
      isShow: false
    };
  },
  // watch: {
  //   "formPur.purchaseMoney":function(){
  //     console.log(244);
  //     let arr = this.projectDetail.map((item) => {
  //       return item.assetsPrice * item.assetsNumbers
  //     })
  //     let account = arr.reduce((sum, current, index) => {
  //       return sum + current
  //     }, 0);
  //     return account
  //   }
  // },
  computed: {
    // 某列求和
    // this.formPur.purchaseMoney: function () {

    purchaseMoney: function () {
      let arr = this.projectDetail.map((item) => {
        return item.assetsPrice * item.assetsNumbers
      })
      let account = arr.reduce((sum, current, index) => {
        return sum + current
      }, 0);
      this.formPur.purchaseMoney = account;
      return account
    },
  },
  methods: {

    addDetail() {
      this.projectDetail.push({
        assetsType: "",
        assetsName: "",
        assetsSpecs: "",
        assetsUnit: "",
        assetsPrice: "",
        assetsNumbers: "",
        totalPrice: "",
        remark: "",
      })
    },

    // 删除明细
    deleteDetail() {
      this.selectItems.forEach(selectItem => {
        const index = this.projectDetail.findIndex(item => item.budgetDetailed === selectItem);
        this.postForm.schoolBudgetDetailsList.splice(index, 1);
      })
      this.selectIndexs = [];
    },

    // 获取列表信息
    getList() {
      this.loading = true;
      purchaseList(this.queryParams).then(response => {
        this.purchaseList = response.rows;
        console.log(this.purchaseList, '  this.purchaseList');
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
      })
    },
    /** 切换tab标签 */
    handleClick({ name }) {
      console.log(name, 'name');
      this.$set(this.queryParams, 'submitState', name);
      // console.log(name, 123);
      if (name == 0) {
        this.isShow = false
        console.log(this.isShow);
      } else {
        this.isShow = true
        console.log(this.isShow);
      }

      //this.resetQuery();
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 提交申请
    submitApply(row) {
      var obj = { applyUser: row.applyUser }
      submitPurchaseList(row.id, obj).then(() => {
        this.$modal.msgSuccess("提交成功");
        this.getList();
      }).catch(() => {
      })
    },
    readNodes(nodes = [], arr = []) {
      for (let item of nodes) {
        arr.push({ id: item.id, label: item.label })
        if (item.children && item.children.length) this.readNodes(item.children, arr)
      }
      return arr
    },
    formReady() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
        let arr = this.readNodes(this.deptOptions)
        this.getDefaultDep()//获取默认部门
        this.getBudgetNamexl()//根据部门id获批复项目下拉框
        const node = arr.find(item => {
          if (item.id == this.formPur.deptId) {
            return item
          }
        })
        this.formPur.deptName = node.label
      });

    },

    // 新增
    handleAdd() {
      this.add = false;
      this.title = "新增采购";
      this.formPur = {};
      this.projectDetail = [];
      this.formReady();
      this.openForPur = true;
      this.isEdit = true;

    },
    //查看
    handleView(row) {
      this.add = true;
      this.formPurDisable = true
      this.loading = true
      this.title = "查看采购申请";
      this.openForPur = true;
      this.multiple = true;
      this.submit = '0';
      this.formReady();
      this.isEdit = false;
      getPurchaseListDetaial(row.id).then(response => {
        this.formPur = response.data;
        this.projectDetail = response.data.list
        this.loading = false
      }).catch(() => {
      })
    },
    // 修改
    handleUpdate(row) {
      this.add = false;
      this.loading = true
      this.title = "修改采购申请";
      this.isEdit = true;
      this.openForPur = true;
      this.submit = '1';
      this.formReady();
      getPurchaseListDetaial(row.id).then(response => {
        this.formPur = response.data;
        this.projectDetail = response.data.list
        this.loading = false
      }).catch(() => {
      })
    },

    // 删除
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除？').then(function () {
        console.log(id, 260);
        return delPurchaseList(id);
      }
      ).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    //  取消
    cancelPur() {
      this.formPurDisable = false;
      this.formPur = {};
      this.openForPur = false;
    },
    /** 提交按钮 */
    submitForm() {
      this.formPur.list = this.projectDetail;
      this.$refs["formPur"].validate(valid => {
        if (valid) {
          if (this.formPur.id != undefined) {
            editPurchaseList(this.formPur).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openForPur = false;
              this.getList();
              this.formPur = {}
            });
          } else {
            addPurchaseList(this.formPur).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.openForPur = false;
              this.getList();
              this.formPur = {}
            });
          }
        }
      });
    },
    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      // this.loading = true;
      // purchaseListByTitle(this.queryParams.title).then(response => {
      //   this.purchaseList = response.rows;
      //   this.total = response.total;
      //   this.loading = false;
      // }).catch(() => {
      // })
    },
    //获校领导下拉框、
    schoolLeader() {
      getLeaderList().then(((res) => {
        if (res.code == 200) {
          this.schoolLeaderList = res.rows
        }
      }))
    },
    // 分管领导
    leaderfgc(data) {
      const { handUserName1, handUserId1 } = data;
      this.formPur.handUserName1 = handUserName1;
      this.formPur.handUserId1 = handUserId1;
    },
    // 财务领导
    leadercw(data) {
      const { handUserName2, handUserId2 } = data;
      this.formPur.handUserName2 = handUserName2;
      this.formPur.handUserId2 = handUserId2;
    },
    // 增加项目明细
    addRow() {
      this.projectDetail.unshift(
        {
          assetsType: "",
          assetsName: "",
          assetsSpecs: "",
          assetsUnit: "",
          assetsPrice: "",
          assetsNumbers: "",
          totalPrice: "",
          remark: "",
        }
      )
      // let obj = {create: this.createIndex++};
      // this.projectDetail.push(obj);
      this.isEdit = true;
    },
    // 多选框选中数据
    handleSelectionChangeDetail(selection) {
      this.id2s = selection.map(item => item.create);
      console.log(this.id2s);
      // this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 删除项目明细
    delRow(index) {
      // this.$modal.confirm('是否确认删除？').then(()=>{
      //   this.projectDetail.splice(index, 1);
      // })
      const keys = this.id2s || [];
      keys.forEach(key => {
        const index = this.projectDetail.findIndex(item => item.create === key);
        this.projectDetail.splice(index, 1);
      });
    },
    //  获取资产分类
    getType() {
      getAssetsType().then(response => {
        this.assetsOptions = response.data;
      }).catch(() => {
      })
    },
    assetsIdAndName(node) {

      let index = this.index
      let arr = this.projectDetail[index]
      arr.assetsType = node.id;
      arr.assetsTypeName = node.label;
      console.log(arr, 594)
      this.$set(this.projectDetail, index, { ...arr })

    },
    // 获取部门
    // getDeptName(){
    //   getDeptTree().then(response=>{
    //     // console.log(response,428);
    //     // this.deptList=response.
    //   }).catch(()=>{})
    // },
    deptIdAndName(node) {
      this.formPur.deptName = node.label;
      this.$set(this.formPur, 'budgetId', undefined);
      this.$nextTick(() => {
        this.getBudgetNamexl()
        this.refreshValidate()
      })
    },
    refreshValidate() {
      this.formPurDisable = false;
      this.$nextTick(() => {
        this.$refs.formPur.clearValidate()
      })

    },

    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 获取批复项目
    getBudgetName(id) {
      this.formPur.budgetName = this.budgetList.find(item => item.id === id)?.budgetName;
      this.formPur.kyye = this.budgetList.find(item => item.id === id)?.kyye;
      console.log(this.formPur.kyye, 'this.formPur.kyye');
      // const {budgetName, budgetId} = data;
      // this.formPur.budgetName = budgetName;
      // this.formPur.budgetId = budgetId;
      // getBudgetList().then(response=>{
      //   this.budgetList=response.rows;
      // }).catch(()=>{})
    },
    //获批复项目下拉框
    getBudgetNamexl() {
      getBudgetList1({ deptId: this.formPur.deptId }).then(((res) => {
        if (res.code == 200) {
          this.budgetList = res.rows
          this.formPur.kyye = this.formPur.kyye
          console.log(this.formPur.kyye, 'this.formPur.kyye');
          console.log(this.budgetList, ' this.budgetList');
        }
      }))
    },
    // 选择资产分类
    selectAssetsType(index) {
      this.title = "选择资产分类";
      this.drawer = true;
      if (this.projectDetail[index]['assetsType'] !== '') {
        console.log(652)
        this.$set(this.formPur, 'assetsType', this.projectDetail[index]['assetsType'])
      }

      this.index = index;
    },
    //获取默认部门
    getDefaultDep() {
      this.formPur.deptId = this.$store.state.user.deptId
    },

    resolveState(taskName) {
      if (taskName == "未启动") {
        return "info"
      } else if (taskName == "处室领导审批") {
        return "warning"
      } else if (taskName == "财务领导审批") {
        return "success"
      } else if (taskName == "已结束") {
        return "danger"
      }

    },
    selectBoss1(val) {
      this.teacherOptions.open = true;
      this.teacherOptions.token = val
    },

    getTeacherList(queryForm, callback) {
      teacherListInform({ ...queryForm, employeeType: 0 }).then(response => {
        callback(response.rows, response.total);
      }).catch(error => {
        callback([], 0);
      })
    },

    setTeacherInfo(item) {
      // this.form.teacherName = item.teacherName;
      if (this.teacherOptions.token === 1) {
        this.$set(this.formPur, 'handUserName1', item.teacherName);
        this.$set(this.formPur, 'handUserId1', item.id);
      } else {
        this.$set(this.formPur, 'handUserName2', item.teacherName);
        this.$set(this.formPur, 'handUserId2', item.id);
      }

    },

  },
  created() {
    this.getList();
    this.schoolLeader();
    this.getType();
    // this.getBudgetNamexl();//获批复项目下拉框


    // this.deptIdAndName();
    // this.assetsIdAndName();
  },
};
</script>
<style scoped lang="less"></style>
