<template>
  <el-dialog title="计算绩效" :visible.sync="visible" width="800px" append-to-body>
    <div class="performance-list">
      <div v-for="(item, index) in performanceList" :key="index" class="performance-item">
        <div class="item-header">
          <span>工作项目 {{ index + 1 }}</span>
          <el-button type="text" icon="el-icon-delete" @click="removeItem(index)"
            v-if="performanceList.length > 1">删除</el-button>
        </div>
        <el-form ref="form" :model="item" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="工作项目">
                <el-select v-model="item.workItem" placeholder="请选择工作项目"
                  @change="(val) => handleWorkItemChange(val, index)">
                  <el-option v-for="workItem in workItemList" :key="workItem.value" :label="workItem.label"
                    :value="workItem.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="内容细项">
                <el-select v-model="item.subItem" placeholder="请选择内容细项"
                  @change="(val) => handleSubItemChange(val, index)">
                  <el-option v-for="subItem in item.workSelect.subItemList" :key="subItem.value" :label="subItem.label"
                    :value="subItem.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="比例尺/等级">
                <el-select v-model="item.scaleGrade" placeholder="请选择比例尺/等级"
                  @change="(val) => handleScaleGradeChange(val, index)">
                  <el-option v-for="scale in item.workSelect.scaleGradeList" :key="scale.value" :label="scale.label"
                    :value="scale.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地类类型">
                <el-select v-model="item.groundType" placeholder="请选择地类类型"
                  @change="(val) => handleGroundTypeChange(val, index)">
                  <el-option key="一般地类" label="一般地类" value="0"></el-option>
                  <el-option key="复杂地类" label="复杂地类" value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="系数">
                <el-input-number v-model="item.coefficient" :precision="2" :step="0.1" :min="0"
                  @change="() => calculateTotal(index)"></el-input-number>
                <el-tooltip content="系数备注" placement="right-start">
                  <el-button icon="el-icon-info" type="text"
                    @click="() => getCoefficientRemark(item.workType)"></el-button>
                </el-tooltip>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工作量">
                <el-input-number v-model="item.workload" :precision="2" :step="0.1" :min="0"
                  @change="() => calculateTotal(index)"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="单价">
            <el-tag>{{ item.price }}/ {{ item.unit }}</el-tag>
          </el-form-item>

          <el-form-item label="单项总额">
            <el-tag>{{ item.total }}</el-tag>
          </el-form-item>

          <el-form-item label="备注">
            {{ item.remark }}
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="add-item">
      <el-button type="primary" icon="el-icon-plus" @click="addItem">添加工作项目</el-button>
    </div>

    <div class="total-amount">
      <span>绩效总额：</span>
      <span class="amount">{{ totalAmount }}</span>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getWorkItemList, getSubItemList, getScaleGradeList, getUnitPrice, getPriceRemarkByWorkType } from '@/api/oa/price/checkPrice'

export default {
  name: 'CalculatePerformance',
  data() {
    return {
      visible: false,
      workItemList: [],
      performanceList: [this.getDefaultItem()]
    }
  },
  computed: {
    totalAmount() {
      return this.performanceList.reduce((sum, item) => {
        return sum + (parseFloat(item.total) || 0)
      }, 0).toFixed(2)
    }
  },
  methods: {
    getDefaultItem() {
      return {
        workItem: '',
        subItem: '',
        scaleGrade: '',
        groundType: '0',
        price: 0,
        workload: 0,
        coefficient: 1,
        total: 0,
        remark: '',
        workSelect: {
          subItemList: [],
          scaleGradeList: []
        }
      }
    },
    open() {
      this.visible = true
      this.resetForm()
      this.initWorkItemList()
    },
    resetForm() {
      this.performanceList = [this.getDefaultItem()]
    },
    addItem() {
      this.performanceList.push(this.getDefaultItem())
    },
    removeItem(index) {
      this.performanceList.splice(index, 1)
    },
    initWorkItemList() {
      getWorkItemList({ workType: '内业' }).then(res => {
        if (res) {
          this.workItemList = this.setArray(res)
        }
      })
    },
    handleWorkItemChange(value, index) {
      const item = this.performanceList[index]
      item.subItem = ''
      item.scaleGrade = ''
      item.price = 0
      item.workSelect.subItemList = []
      item.workSelect.scaleGradeList = []
      this.calculateTotal(index)

      if (value) {
        this.getWorkSubItemList(item, value)
      }
    },
    getWorkSubItemList(item, workItem) {
      getSubItemList({ workItem }).then(res => {
        if (res) {
          let subItemList = this.setArray(res)
          item.workSelect.subItemList = subItemList
          if (subItemList.length > 0) {
            item.subItem = subItemList[0].value
            this.handleSubItemChange(item.subItem, this.performanceList.indexOf(item))
          }
        }
      })
    },
    handleSubItemChange(value, index) {
      const item = this.performanceList[index]
      item.scaleGrade = ''
      item.price = 0
      item.workSelect.scaleGradeList = []
      this.calculateTotal(index)

      // Set remark based on selected subItem
      const selectedSubItem = item.workSelect.subItemList.find(sub => sub.value === value)
      if (selectedSubItem) {
        item.remark = selectedSubItem.remark || ''
      }

      if (value && item.workItem) {
        getScaleGradeList({ workItem: item.workItem }).then(res => {
          if (res) {
            let scaleGradeList = this.setArray(res)
            item.workSelect.scaleGradeList = scaleGradeList
            if (scaleGradeList.length > 0) {
              item.scaleGrade = scaleGradeList[0].value
              this.handleScaleGradeChange(item.scaleGrade, index)
            }
          }
        })
      }
    },
    handleScaleGradeChange(value, index) {
      const item = this.performanceList[index]
      item.price = 0
      this.calculateTotal(index)

      if (value && item.workItem && item.subItem) {
        this.getUnitPrice(index)
      }
    },
    handleGroundTypeChange(value, index) {
      const item = this.performanceList[index]
      item.price = 0
      this.calculateTotal(index)

      if (item.scaleGrade && item.workItem && item.subItem) {
        this.getUnitPrice(index)
      }
    },
    getUnitPrice(index) {
      const item = this.performanceList[index]
      getUnitPrice({
        workItem: item.workItem,
        subItem: item.subItem,
        scaleGrade: item.scaleGrade,
        groundType: item.groundType
      }).then(res => {
        if (res.length != 0) {
          item.price = res.data.price
          item.unit = res.data.unit
          item.remark = res.data.remark || ''
          this.calculateTotal(index)
        }
      })
    },
    calculateTotal(index) {
      const item = this.performanceList[index]
      item.total = ((parseFloat(item.price) * parseFloat(item.coefficient) * parseFloat(item.workload))).toFixed(2)
    },
    handleConfirm() {
      this.$emit('confirm', this.totalAmount)
      this.visible = false
    },
    getCoefficientRemark(workType) {
      if (workType) {
        getPriceRemarkByWorkType({ workType }).then(res => {
          if (res.code == 200) {
            this.$notify({
              title: workType,
              dangerouslyUseHTMLString: true,
              message: res.msg,
              duration: 0
            })
          }
        })
      }
    },
    setArray(arr) {
      if (arr != [] && arr != undefined) {
        let datalist = [...new Set(arr)]
        let list = []
        for (let i of datalist) {
          let obj = new Object()
          obj.label = i
          obj.value = i
          list.push(obj)
        }
        return list
      } else {
        return []
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.performance-list {
  max-height: 600px;
  overflow-y: auto;
  padding: 10px;
}

.performance-item {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 15px;
  position: relative;

  .item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #EBEEF5;

    span {
      font-size: 16px;
      font-weight: bold;
    }
  }
}

.add-item {
  text-align: center;
  margin: 15px 0;
}

.total-amount {
  text-align: right;
  padding: 15px;
  font-size: 16px;
  border-top: 1px solid #EBEEF5;
  margin-top: 15px;

  .amount {
    color: #F56C6C;
    font-size: 20px;
    font-weight: bold;
    margin-left: 10px;
  }
}
</style>