<template>
  <Dialog title="修改" v-model="visible" width="80%">
    <el-form
      ref="form"
      :model="entityData"
      :rules="rules"
      label-width="120px"
      label-position="right"
      style="width: 90%; margin: 0px auto"
    >
      <!--表单区域 -->
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="entityData.projectName" />
      </el-form-item>
      <el-form-item label="总投资" prop="totalInvestment">
        <el-input type="number" v-model="entityData.totalInvestment" disabled />
      </el-form-item>
    </el-form>
    <!--表格区域-->

    <avue-crud
      ref="crudRef"
      v-model="curdForm"
      v-model:defaults="defaults"
      :option="option"
      :data="tableData"
      @row-update="addUpdate"
      @row-save="rowSave"
      @row-del="rowDelete"
    >
      <template #orderNo="{ row }">
        <el-tag type="success">{{ row.orderNo }}</el-tag>
      </template>
      <template #menu-left="{}">
        <el-button
          type="danger"
          icon="el-icon-plus"
          @click="addrow()"
          v-permission="pageCode + 'add'"
          >新增</el-button
        >
      </template>
      <template #menu="{ row, index }">
        <el-button text type="primary" @click="addChild(row, index)" v-if="row.isDetail == '0'"
          >增加子项</el-button
        >
      </template>
      <template #costName-form="{}">
        <costTypeComponents v-model="curdForm.costName" :module-param="moduleParam" @updateCostInfo="updateCostInfo"/>
      </template>
    </avue-crud>

    <template #footer>
      <el-button type="primary" @click="save" v-permission="pageCode + 'add'">保存</el-button>
      <el-button @click="close">关闭</el-button>
    </template>
  </Dialog>
</template>

<script>
import { Dialog } from '@/components/abc/Dialog'
import costTypeComponents from '@/modules/costManagement/components/costTypeComponents.vue'

const MODULE_CODE = 'costManagement'
const ENTITY_TYPE = 'costTable'
export default {
  name: ENTITY_TYPE + '-modify',
  components: { Dialog,costTypeComponents },
  data() {
    return {
      entityType: ENTITY_TYPE,
      moduleCode: MODULE_CODE,
      // eslint-disable-next-line no-eval
      api: eval('this.$api.' + MODULE_CODE + '.' + ENTITY_TYPE),
      pageCode: MODULE_CODE + ':' + ENTITY_TYPE + ':',
      entityData: {},
      visible: false,
      rules: {
        //前端验证规则
        projectName: [{ required: true, message: '【项目名称】不能为空', trigger: 'blur' }],
        totalInvestment: [{ required: true, message: '【总投资】不能为空', trigger: 'blur' }]
      },
      tableData: [],
      curdForm: {},
      defaults: {},
      parentId: undefined,
      currentlevel: undefined,
      currentRowData: {},
      option: {
        addBtn: false,
        refreshBtn: false,
        columnBtn: false,
        gridBtn: false,
        index: false,
        rowKey: 'id',
        rowParentKey: 'parentId',
        menuWidth: 100,
        column: {
          orderNo: {
            label: '序号',
            display: false,
            width:200
          },
          isDetail: {
            label: '是否明细',
            type: 'radio',
            button: true,
            dicData: [
              {
                label: '是',
                value: '1'
              },
              {
                label: '否',
                value: '0'
              }
            ],
            value: '0',
            rules: [
              {
                required: true
              }
            ],
            hide: true
          },
          costType: {
            label: '费用类型',
            rules: [
              {
                required: true,
                message: '请输入费用类型',
                trigger: 'blur'
              }
            ]
          },
          constructContent: {
            label: '建设内容',
            span: 24,
            type: 'textarea',
            rules: [
              {
                required: true,
                message: '请输入建设内容',
                trigger: 'blur'
              }
            ]
          },
          costName: {
            label: '费用名称',
            rules: [
              {
                required: true,
                message: '请输入费用名称',
                trigger: 'blur'
              }
            ]
          },
          costDescribe: {
            label: '费用描述',
            span: 24,
            type: 'textarea',
            rules: [
              {
                required: true,
                message: '请输入费用描述',
                trigger: 'blur'
              }
            ]
          },
          //
          unit: {
            label: '单位',
            rules: [
              {
                required: true,
                message: '请输入单位',
                trigger: 'blur'
              }
            ]
          },
          quantity: {
            label: '数量',
            type: 'number',
            min: 1,
            precision: 0,
            rules: [
              {
                required: true,
                message: '请输入数量',
                trigger: 'blur'
              }
            ]
          },
          unitPrice: {
            label: '单价',
            type: 'number',
            min: 0,
            precision: 2,
            rules: [
              {
                required: true,
                message: '请输入单价',
                trigger: 'blur'
              }
            ]
          },
          totalPrice: {
            label: '总价',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请输入总价',
                trigger: 'blur'
              }
            ]
          },
          remarks: {
            label: '备注'
          }
        }
      }
    }
  },
  methods: {
    // 初始化
    init(id) {
      this.api.getCostTableDetail(id).then((res) => {
        this.entityData = res.data
        this.tableData = res.data.costItemDetailList
        this.visible = true
      })
    },
    //增加父项
    addrow() {
      this.currentlevel = this.tableData.length + 1
      this.$refs.crudRef.rowAdd()
    },
    addUpdate(row, index, done, loading) {
      console.log('addUpdate', row)
      done(row)
      this.updatePrice()
    },
    rowSave(row, done) {
      row.costTableId = this.entityData.id
      row.parentId = this.parentId
      row.id = new Date().getTime()
      row.orderNo = this.currentlevel
      this.currentlevel = undefined
      this.parentId = undefined
      console.log('rowSave', row, this.data)
      done(row)
      this.updatePrice()
    },
    rowDelete(row, index, done) {
      console.log('rowDelete', row)
      done(row)
      this.updatePrice()
    },
    //增加子项
    addChild(row, index) {
      //如果当前行已经有子项了，是否设备字段与子项一致，否则默认为非设备
      if (row.children && row.children.length > 0) {
        this.curdForm.isDetail = row.children[0].isDetail
      } else {
        this.curdForm.isDetail = '0'
      }
      this.parentId = row.id
      this.currentlevel =
        row.orderNo + '-' + (row.children == undefined ? 1 : row.children.length + 1)
      this.$refs.crudRef.rowAdd()
    },
    calculateSubtotal(item) {
      if (item.isDetail == '1') {
        return item.totalPrice
      }
      let subtotal = 0
      if (item.children && item.children.length > 0) {
        subtotal += item.children.reduce((acc, child) => acc + this.calculateSubtotal(child), 0)
      }
      item.totalPrice = subtotal
      if (item.children) {
        for (let i = 0; i < item.children.length; i++) {
          if (item.children[i].isDetail == '0') {
            //不是设备计算总价
            item.children[i].totalPrice = this.calculateSubtotal(item.children[i])
          }
        }
      }
      return subtotal
    },
    updatePrice() {
      this.entityData.totalInvestment = 0
      if (this.tableData.length > 0) {
        this.tableData.forEach((item) => {
          this.calculateSubtotal(item)
          this.entityData.totalInvestment += item.totalPrice
          console.log('calculateSubtotal', item, this.entityData)
        })
      }
    },
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.entityData.costItemDetailList = this.tableData
          this.api.modifyCostTable(this.entityData).then((response) => {
            this.close()
          })
        }
      })
    },
    updateCostInfo(val){
      this.curdForm.costDescribe = val.modelDescription
      this.curdForm.unitPrice=val.productPrice
    },
    close() {
      this.visible = false
      this.$emit('refresh')
    }
  },
  computed: {
    updatedTotal() {
      return this.curdForm.unitPrice * this.curdForm.quantity
    }
  },
  watch: {
    //监听表单数据，对表单字段属性进行设置
    'curdForm.isDetail'(val) {
      console.log('isDetail', val, this.curdForm, this.defaults)
      if (val == '0') {
        //不是设备
        this.defaults.costName.display = false
        this.defaults.costDescribe.display = false
        this.defaults.unit.display = false
        this.defaults.quantity.display = false
        this.defaults.unitPrice.display = false
        this.defaults.totalPrice.display = false
        this.curdForm.costName = ''
        this.curdForm.costDescribe = ''
        this.curdForm.unit = ''
        this.curdForm.quantity = ''
        this.curdForm.unitPrice = ''
        this.curdForm.totalPrice = ''
        this.defaults.costType.display = true
        this.defaults.constructContent.display = true
      } else {
        this.defaults.costType.display = false
        this.defaults.constructContent.display = false
        this.curdForm.costType = ''
        this.curdForm.constructContent = ''
        this.defaults.costName.display = true
        this.defaults.costDescribe.display = true
        this.defaults.unit.display = true
        this.defaults.quantity.display = true
        this.defaults.unitPrice.display = true
        this.defaults.totalPrice.display = true
      }
    },
    updatedTotal(val) {
      if (val == 0) {
        this.curdForm.totalPrice = '' //如果总价为0，则不显示
        return
      }
      this.curdForm.totalPrice = val //监听updatedTotal，更新总价
    },
    tableData: {
      handler(val, oldVal) {
        console.log('tableData', val, oldVal)
      },
      deep: true
    }
  }
}
</script>

<style></style>
