<template>
  <div>
    <el-drawer
      size="64%"
      :title="type === 1 ? '年中绩效指标' : '年末绩效指标'"
      :visible.sync="isShow"
      direction="rtl"
    >
      <xy-table
        ref="table"
        :list="list"
        :table-item="tableItem"
        :default-expand-all="false"
        @expand-change="expandChange"
      >
        <template v-slot:btns> </template>
      </xy-table>

      <el-popover placement="left" width="200" trigger="click" v-if="plan.year_midst_status == 1">
        <div style="margin-bottom: 15px;">确认年中自评确认?</div>
        <div style="margin-top:15px; display: flex;justify-content: flex-end;">
          <Button type="primary" ghost size="small" @click="() => edit(plan,'year_midst_status')">确认</Button>
        </div>
        <Button
          slot="reference"
          type="primary"
          class="slot-btns-item"
          style="margin: 10px;"
        >
          年中自评确认
        </Button>
      </el-popover>

      <el-popover placement="left" width="200" trigger="click" v-if="plan.year_end_status == 1">
        <div style="margin-bottom: 15px;">确认年末自评确认?</div>
        <div style="margin-top:15px; display: flex;justify-content: flex-end;">
          <Button type="primary" ghost size="small" @click="() => edit(plan,'year_end_status')">确认</Button>
        </div>
        <Button
          style="margin-right: 5px;"
          slot="reference"
          type="primary"
          class="slot-btns-item"
        >
          年末自评确认
        </Button>
      </el-popover>
    </el-drawer>
  </div>
</template>

<script>
import { index } from "@/api/budget/planTarget";
import { save, show, index as evaluateIndex } from "@/api/achievements/evaluate"
import { deepCopy, resetSelect } from '@/utils'
import { getToken } from "@/utils/auth";
import { editorBudget } from '@/api/budget/budget'
import { getparameter } from '@/api/system/dictionary'

export default {
  data() {
    return {
      symbols: [],
      units: [],
      isShow: false,
      type: 1,
      action: process.env.VUE_APP_UPLOAD_API,

      list: [],
      table: [
        {
          type: "expand",
          width: 80,
          label: "自评展开",
          expandFn: ({ row, $index, store }) => {
            row._form.score = row.score
            return (
              <div class="expand">
                <el-form
                  ref={`expand-form${$index}`}
                  props={{ model: row._form }}
                  label-width="120px"
                >
                  <el-form-item label="实际完成值" required={true}>
                    <el-input
                      type="textarea"
                      autosize={{
                        minRows: 3,
                      }}
                      v-model={row._form.result}
                      size="small"
                      placeholder="请输入实际完成值"
                    ></el-input>
                  </el-form-item>

                  <el-form-item label="得分" required={true}>
                    <el-input-number
                      precision={2}
                      controls={false}
                      vModel={row._form.score}
                      size="small"
                      min={0}
                      max={100}
                      placeholder="请输入自评值"
                    ></el-input-number>
                  </el-form-item>

                  <el-form-item label="备注及未完成指标原因分析">
                    <el-input
                      type="textarea"
                      autosize={{
                        minRows: 3,
                      }}
                      v-model={row._form.remark}
                      size="small"
                      placeholder="请输入备注及未完成指标原因分析"
                    ></el-input>
                  </el-form-item>

                  <el-form-item label="文件">
                    <el-upload
                      style="width: 300px"
                      ref={`expand-form-upload${$index}`}
                      multiple={true}
                      headers={{
                        Authorization: "Bearer " + getToken(),
                      }}
                      before-upload={this.uploadBefore}
                      props={{
                        onSuccess: (response, file, fileList) => {
                          this.successHandle(response, file, fileList, row);
                        },
                        onRemove: (file, fileList) => {
                          this.removeHande(file, fileList, row);
                        },
                      }}
                      accept="application/x-rar-compressed,application/zip,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/pdf"
                      action={this.action}
                      file-list={row._fileList}
                      auto-upload={false}
                    >
                      <el-button slot="trigger" size="small" type="primary">
                        选取文件
                      </el-button>
                      <el-button
                        style="margin-left: 10px"
                        size="small"
                        type="success"
                        on={{
                          ["click"]: (e) =>
                            this.$refs[`expand-form-upload${$index}`].submit(),
                        }}
                      >
                        开始上传
                      </el-button>
                      <div slot="tip" className="el-upload__tip">
                        支持文件格式：.rar .zip .doc .docx .pdf
                        <br />
                        单个文件不能超过500kb
                      </div>
                    </el-upload>
                  </el-form-item>

                  <el-form-item>
                    <el-button
                      type="primary"
                      on={{
                        ["click"]: (e) => {
                          row._form.file_ids = row._fileList?.map(i => i.response.id)
                          save(row._form).then(res => {
                            this.$message({
                              type: "success",
                              message: "操作成功"
                            })
                          })
                        },
                      }}
                    >
                      保存
                    </el-button>
                    <el-button
                      on={{
                        ["click"]: (e) => {
                          this.$refs["table"].toggleRowExpansion(row, false);
                          resetSelect(row._form);
                        },
                      }}
                    >
                      取消
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>
            );
          },
        },
        {
          label: "分值",
          prop: "target.score",
          width: 100,
        },
        {
          label: "指标名称",
          prop: "target.name",
          minWidth: 200,
        },
        {
          label: "评价方式",
          prop: "target.evaluation_way",
          minWidth: 260,
          align: "left"
        },

      ],
      select: {
        page: 1,
        page_size: 999,
        plan_id: "",
      },
      plan: {}
    };
  },
  methods: {
    show() {
      this.isShow = true;
    },
    hidden() {
      this.isShow = false;
    },
    getPlanId() {
      return this.select.plan_id;
    },
    setPlanId(plan_id) {
      this.select.plan_id = plan_id;
    },
    setPlan (plan) {
     this.plan = plan
    },

    //上传
    successHandle(response, file, fileList, row) {
      row._fileList = fileList;
    },
    removeHande(file, fileList, row) {
      row._fileList = fileList;
    },
    uploadBefore(file) {
      if (file.size / 1024 > 500) {
        this.$message({
          type: "warning",
          message: "上传文件大小超过500kb！",
        });
        return false;
      }
    },

    spanMethod({ row, column, rowIndex, columnIndex }) {
      if (column.key === "target_type") {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
      if (column.key === "target_type2") {
        const _row = this.spanArr1[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
    },

    expandChange({ row, expanded }) {
      if(expanded.indexOf(row) !== -1) {
        evaluateIndex({
          type: this.type,
          plan_target_id: row.id
        }).then(res => {
          res.data.length > 0 ? this.$integrateData(row._form,res.data[0]) : ''
          row._fileList = res.data[0]?.files?.map(i => {
            return {
              name: i.name,
              url: i.url,
              response: {
                id: i.id
              }
            }
          })
        })
        // show({ id:2 }).then(res => {
        //   this.$integrateData(row._form,res)
        //   row._fileList = res.files.map(i => {
        //     return {
        //       name: i.name,
        //       url: i.url,
        //       response: {
        //         id: i.id
        //       }
        //     }
        //   })
        // })
      }
    },

    async getList() {
      const res = await index(this.select);
      this.list = res.data.map((item) => {
        return {
          _form: {
            id: "",
            score: "",
            result: "",
            remark: "",
            type: this.type,
            file_ids: [],
            plan_id: this.getPlanId(),
            plan_target_id: item.id,
          },
          _fileList: [],
          ...item,
        };
      });

      console.log(this.list);
    },

    edit(row, key) {
      let rowCopy = deepCopy(row)
      rowCopy[key] = 2
      editorBudget(rowCopy).then(res => {
        this.$message({
          type: 'success',
          message: '确认成功'
        })
        this.getList()
      })
    },

    async getSymbols() {
      const res = await getparameter( { number: "symbol" })
      this.symbols = res.detail
    },
    async getUnits() {
      const res = await getparameter({ number: "unit" })
      this.units = res.detail
    },
    submit() {},
  },
  computed: {
    tableItem () {
      let temp = this.table
      return [
        ...this.table,
        {
          label: temp === 1 ? '半年（程）指标值' : '全年（程）指标值',
          width: 180,
          customFn: row => (
            <div>
              {
                this.symbols.find(i => i.id === row.target?.symbol_id)?.value === '定性' ? (<span>{ temp === 1 ? row.target?.half_target : row?.target.year_target }</span>) : (
                  <p><span>{ this.symbols.find(i => i.id === row.target?.symbol_id)?.value }</span><span>{ temp === 1 ? row.target?.half_target : row?.target.year_target }</span><span>{ this.units.find(i => i.id === row.target?.unit_id)?.value }</span></p>
                )
              }
            </div>
          )
        }
      ]
    }
  },
  watch: {
    isShow(val) {
      if (val) {
        this.getList();
      } else {
        this.list = [];
      }
    },
  },
  created() {
    this.getSymbols()
    this.getUnits()
  }
};
</script>

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