<template>
  <!-- 上传交付物 -->
  <view class="py-2">
    <u-input :auto-height="autoHeight" :border="border" :height="height" :type="type" v-model="content" width="100" />

    <!-- 选择检查人 -->
    <ChooseChecker ref="checker" :checkerList="checkerList" @setCheckerList="setCheckerList"></ChooseChecker>

    <view class="flex justify-between">
      <u-button @click="submit" class="m-0" size="mini" type="primary">提交</u-button>
      <u-icon @click="changeShowHistory" name="arrow-up" v-if="showHistory"></u-icon>
      <u-icon @click="changeShowHistory" name="arrow-down" v-else></u-icon>
    </view>

    <p-delivery-history :task="task" v-if="showHistory" />
  </view>
</template>

<script>
import ChooseChecker from '@/components/ChooseChecker/ChooseChecker.vue';
import { mapState, mapGetters } from 'vuex';

export default {
  name: 'p-upload-deliverable',
  components: { ChooseChecker },
  props: { task: { type: Object, default: null } },
  data() {
    return {
      content: '',
      type: 'textarea',
      border: true,
      height: 30,
      autoHeight: true,
      checkerList: [],
      showHistory: false, // 展开历史记录
    };
  },

  computed: {
    ...mapState('role', ['members']),
    ...mapGetters('project', ['projectId']),

    checkers() {
      const arr = [];
      if (this.members.length) {
        this.members.forEach(member => {
          const item = { value: member.memberId, label: member.name };
          arr.push(item);
        });
      }
      return arr;
    },
  },

  methods: {
    // 设置检查人
    setCheckerList(checked, item) {
      if (checked) {
        this.checkerList.push(item.memberId);
      } else {
        const index = this.checkerList.findIndex(checker => checker === item.memberId);
        this.checkerList.splice(index, 1);
      }
    },

    // 展开合上历史记录
    changeShowHistory() {
      this.showHistory = !this.showHistory;
    },

    // 提交交付物
    async submit() {
      try {
        const { content, checkerList, projectId, task } = this;
        if (!this.checkerList.length) {
          this.$t.ui.showToast('请选择检查人');
          return;
        }
        const params = { content, checkerList, projectId, taskSubId: task.id };
        await this.$u.api.saveDeliver(params);
        this.$t.ui.showToast('交付物提交成功');
        this.content = '';
        this.checkerList = [];
        this.$refs.checker.clearChecked();
      } catch (error) {
        console.error('p-upload-deliverable.vue submit error: ', error);
        this.$t.ui.showToast('交付物提交失败，请稍后重试');
      }
    },
  },
};
</script>

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