<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目编号" prop="projectNumber">
        <el-input v-model="queryParams.projectNumber" placeholder="请输入项目编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" 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">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['oa:brandProject:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['oa:brandProject:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['oa:brandProject:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['oa:brandProject:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="brandProjectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目进度" align="center" width="120px">
        <template slot-scope="scope">
          <el-progress :text-inside="true" :stroke-width="26" :status="formartProjectProgress(scope.row.percentage)"
            :percentage="scope.row.percentage" text-color="#fff"></el-progress>
        </template>
      </el-table-column>
      <el-table-column label="项目编号" align="center" prop="projectNumber" width="120px" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="甲方单位" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.partyA && scope.row.partyA.partyAName == null">
            {{ scope.row.partyAId.split(',').map(id => {
              const partyA = partyAList.find(item => item.partyAId === id);
              return partyA ? partyA.partyAName : '';
            }).filter(Boolean).join(', ') }}
          </span>
          <span v-else-if="scope.row.partyA && scope.row.partyA.partyAName">
            {{ scope.row.partyA.partyAName }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="甲方单位联系人" align="center" prop="aPerson" />
      <el-table-column label="甲方单位联系电话" align="center" prop="aPhone" /> -->
      <el-table-column label="合作单位" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.partner && scope.row.partner.partnerName == null">
            {{ scope.row.partnerId.split(',').map(id => {
              const partner = partnerList.find(item => item.partnerId === id);
              return partner ? partner.partnerName : '';
            }).filter(Boolean).join(', ') }}
          </span>
          <span v-else-if="scope.row.partner && scope.row.partner.partnerName">
            {{ scope.row.partner.partnerName }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="合作单位联系人" align="center" prop="contactPerson" />
      <el-table-column label="合作单位联系电话" align="center" prop="telephone" /> -->
      <el-table-column label="项目工期" align="center" prop="duration" />
      <el-table-column label="合同金额" align="center" prop="amount" width="100px" />
      <!-- <el-table-column label="项目概况" align="center" prop="content" /> -->
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleLook(scope.row)"
            v-hasPermi="['oa:brandProject:query']">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['oa:brandProject:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['oa:brandProject:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改cmc品牌项目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :disabled="isView">
        <el-descriptions class="margin-top" :column="2" border>
          <el-descriptions-item>
            <template slot="label">
              <span class="require_input">* </span>项目编号
            </template>
            <el-form-item prop="projectNumber">
              <el-input v-model="form.projectNumber" placeholder="请输入项目编号" />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <span class="require_input">* </span>项目名称
            </template>
            <el-form-item prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :span="2">
            <template slot="label">
              甲方单位
            </template>
            <el-form-item label="甲方单位" prop="partyAId">
              <el-select v-model="form.partyAId" multiple filterable placeholder="请选择" disabled style="width: 80%;" clearable>
                <el-option v-for="item in partyAList" :key="item.partyAId" :label="item.partyAName" :value="item.partyAId">
                </el-option>
              </el-select>
              <el-button type="primary" @click="partyAOpen = true">选择单位</el-button>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              甲方单位联系人
            </template>
            <el-form-item prop="aPerson">
              <el-input v-model="form.aPerson" placeholder="请输入甲方单位联系人" />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              甲方单位联系电话
            </template>
            <el-form-item prop="aPhone">
              <el-input v-model="form.aPhone" placeholder="请输入甲方单位联系电话" />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :span="2">
            <template slot="label">
              合作单位
            </template>
            <el-form-item label="合作单位" prop="partnerId">
              <el-select allow-create v-model="form.partnerId" multiple filterable placeholder="请选择" style="width: 80%;" disabled
                clearable>
                <el-option v-for="item in partnerList" :key="item.value" :label="item.partnerName"
                  :value="item.partnerId">
                </el-option>
              </el-select>
              <el-button type="primary" @click="partnerOpen = true">选择单位</el-button>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              合作单位联系人
            </template>
            <el-form-item prop="contactPerson">
              <el-input v-model="form.contactPerson" placeholder="请输入合作单位联系人" />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              合作单位联系电话
            </template>
            <el-form-item prop="telephone">
              <el-input v-model="form.telephone" placeholder="请输入合作单位联系电话" />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :span="2">
            <template slot="label">
              项目概况
            </template>
            <el-form-item prop="content">
              <el-input type="textarea" v-model="form.content" placeholder="请输入项目概况" />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              项目工期
            </template>
            <el-form-item prop="duration">
              <el-input v-model="form.duration" placeholder="请输入项目工期" />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              合同金额
            </template>
            <el-form-item prop="amount">
              <el-input v-model="form.amount" placeholder="请输入合同金额">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :span="2">
            <template slot="label">
              备注
            </template>
            <el-form-item prop="remark">
              <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
        <el-divider></el-divider>
        <el-form-item label="项目进度：">
          <table border="1" style="width:100%">
            <tr>
              <td style="width: 80px">序号</td>
              <td>截至日期</td>
              <td>累计总进度（%）</td>
              <td style="width: 300px">情况说明</td>
              <td style="width: 80px">操作</td>
            </tr>
            <tr v-for="(progress, index) in progressList" :key="index">
              <td>
                {{ index + 1 }}
              </td>
              <td>
                <el-date-picker type="date" placeholder="选择日期" v-model="progress.date"
                  value-format="yyyy-MM-dd"></el-date-picker>
              </td>
              <td>
                <el-input-number v-model="progress.percentage" :controls="false" style="width: 120px"></el-input-number>%
              </td>
              <td>
                <el-input v-model="progress.situation" type="textarea"></el-input>
              </td>
              <td>
                <el-button type="text" icon="el-icon-delete" style="color:#F56C6C" size="mini"
                  @click="deleProgressItem(index)">删除行</el-button>
              </td>
            </tr>
          </table>
          <el-button icon="el-icon-plus" size="mini" @click="addProgressList()" type="primary" plain></el-button>
        </el-form-item>
        <el-form-item label="审核文件：">
          <div v-if="approvalDocument != ''">
            <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + approvalDocument}`)">
              {{ getFileName(approvalDocument) }}
            </el-link>
            <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + approvalDocument}`"
              :underline="false" target="_blank">
              <span class="el-icon-download">下载文件</span>
            </el-link>
          </div>
          <div v-else>
            暂无文件
          </div>
        </el-form-item>
        <el-form-item label="财务反馈：">
          <table border="1" style="width:100%;">
            <tr>
              <td>序号</td>
              <td>到账情况</td>
              <td>到账时间</td>
            </tr>
            <tr v-for="(payment, index) in paymentList" :key="index">
              <td>
                {{ index + 1 }}
              </td>
              <td>
                {{ payment.cwComment }}
              </td>
              <td>
                {{ payment.paymentTime }}
              </td>
            </tr>
          </table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择甲方单位" :visible.sync="partyAOpen" width="60%" append-to-body>
      <choose-party-a @confirm="confirmPartyA"></choose-party-a>
    </el-dialog>
    <el-dialog title="选择合作单位" :visible.sync="partnerOpen" width="60%" append-to-body>
      <choose-partner @confirm="confirmPartners"></choose-partner>
    </el-dialog>
  </div>
</template>

<script>
import { listBrandProject, getBrandProject, delBrandProject, addBrandProject, updateBrandProject } from "@/api/oa/brand/brandProject";
import { listBrandProgress, getBrandProgress, addBrandProgress, delBrandProgress } from "@/api/oa/brand/brandProgress"
import { listPartner, getPartner } from "@/api/oa/partner/partner";
import { listBrandPayment, addBrandPayment, delBrandPayment } from "@/api/oa/brand/brandPayment";
import { listBrand, getBrand } from '@/api/oa/brand/brand';
import { listPartyA } from "@/api/oa/partyA/partyA";
import ChoosePartyA from '@/views/flowable/form/components/choosePartyA.vue';
import ChoosePartner from '@/views/flowable/form/components/choosePartner.vue';

export default {
  name: "BrandProject",
  components: {
    ChoosePartyA,
    ChoosePartner
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // cmc品牌项目表格数据
      brandProjectList: [],
      partnerList: [],
      partyAList: [],
      progressList: [
        {
          date: "",
          percentage: "",
          situation: "",
        },
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      partyAOpen: false,
      partnerOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectNumber: null,
        projectName: null,
        partyA: null,
        aPerson: null,
        aPhone: null,
        partnerId: null,
        contactPerson: null,
        telephone: null,
        duration: null,
        amount: null,
        content: null,
      },
      // 表单参数
      form: {
        partyAId: [],
        partnerId: []
      },
      progress: {},
      // 表单校验
      rules: {
        projectNumber: [{ required: true, message: "项目编号不能为空", trigger: "blur" }],
        projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
      },
      isView: false,
      paymentList: [],
      approvalDocument: ''
    };
  },
  created() {
    this.getPartyAList();
    this.getPartnerList();
    this.getList();
  },
  methods: {
    /** 查询cmc品牌项目列表 */
    getList() {
      this.loading = true;
      listBrandProject(this.queryParams).then(response => {
        this.brandProjectList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.brandProjectList.forEach(item => {
          listBrandProgress({
            pageNum: 1,
            pageSize: 200,
            projectId: item.projectId
          }).then(res => {
            if (res.rows) {
              let len = res.rows.length
              if (len != 0) {
                this.$set(item, 'percentage', Number(res.rows[len - 1].percentage))
              } else {
                this.$set(item, 'percentage', 0)
              }
            }

          })
        })
      });
    },
    confirmPartyA(val) {
      this.partyAOpen = false
      if (val) {
        this.getPartyAList();
        let ids = []
        val.map(item => {
          ids.push(item.partyAId)
        })
        this.$set(this.form, 'partyAId', ids)
      }
    },
    // 确定合作单位
    confirmPartners(val) {
      this.partnerOpen = false
      if (val) {
        let ids = []
        let contactPerson = []
        let telephone = []
        val.map(item => {
          ids.push(item.partnerId)
          if (item.contactPerson)
            contactPerson.push(item.contactPerson)
          if (item.telephone)
            telephone.push(item.telephone)
        })
        this.$set(this.form, 'contactPerson', contactPerson.join(','));
        this.$set(this.form, 'telephone', telephone.join(','));
        this.form.partnerId = ids
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 查询承接单位列表
    getPartnerList() {
      this.loading = true
      listPartner({
        pageNum: 1,
        pageSize: 99999999
      }).then(response => {
        this.partnerList = response.rows;
      })
    },
    // 查询业主单位列表
    getPartyAList() {
      this.loading = true
      listPartyA({
        pageNum: 1,
        pageSize: 99999999
      }).then(response => {
        this.partyAList = response.rows;
      })
    },
    // 选择单位
    handleSelectPartner(val) {
      getPartner(val).then(response => {
        this.$set(this.form, 'contactPerson', response.data.contactPerson);
        this.$set(this.form, 'telephone', response.data.telephone);
      })
    },
    deleProgressItem(index) {
      let arr = this.progressList;
      if (arr.length == 1) {
        return;
      }
      if (index >= 0 && index < arr.length) {
        arr.splice(index, 1);
      }
    },
    addProgressList() {
      this.progressList.push({
        date: "",
        percentage: "",
        situation: "",
      });
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: null,
        projectNumber: null,
        projectName: null,
        partyA: null,
        aPerson: null,
        aPhone: null,
        partyAId: [],
        partnerId: [],
        contactPerson: null,
        telephone: null,
        duration: null,
        amount: null,
        content: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.projectId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "品牌项目登记";
      this.progressList = [{
        date: "",
        percentage: "",
        situation: "",
      }]
    },
    handleLook(row) {
      this.handleUpdate(row)
      this.isView = true;
      this.title = "品牌项目";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      this.isView = false;
      const projectId = row.projectId
      let brandFormData = await listBrand({ projectId })
      let brandId;
      if (brandFormData.total == 1) {
        brandId = brandFormData.rows[0].brandId
        this.approvalDocument = brandFormData.rows[0].approvalDocument
        listBrandPayment({ brandId }).then(result => {
          this.paymentList = result.rows
        })
      } else {
        this.paymentList = []
        this.approvalDocument = ''
      }
      getBrandProject(projectId).then(response => {
        const data = response.data;
        // 将字符串类型的ID转换为数组
        if (data.partyAId) {
          data.partyAId = Array.isArray(data.partyAId) ? data.partyAId : data.partyAId.split(',');
        } else {
          data.partyAId = [];
        }
        if (data.partnerId) {
          data.partnerId = Array.isArray(data.partnerId) ? data.partnerId : data.partnerId.split(',');
        } else {
          data.partnerId = [];
        }
        this.form = data;
        this.open = true;
        this.title = "品牌项目";
      });
      listBrandProgress({
        pageNum: 1,
        pageSize: 200,
        projectId: projectId
      }).then(res => {
        if (res.rows && res.rows.length != 0) {
          this.progressList = res.rows
        } else {
          this.progressList = [{
            date: "",
            percentage: "",
            situation: "",
          }]
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 准备提交数据，将数组转换为字符串
          const submitData = {
            ...this.form,
            partyAId: Array.isArray(this.form.partyAId) ? this.form.partyAId.join(',') : this.form.partyAId,
            partnerId: Array.isArray(this.form.partnerId) ? this.form.partnerId.join(',') : this.form.partnerId
          };
          if (this.form.projectId != null) {
            updateBrandProject(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.updateProjectProgressList();
            });
          } else {
            addBrandProject(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
            this.addProjectProgressList();
          }
        }
      });
    },
    addProjectProgressList() {
      const projectId = this.form.projectId
      this.progressList.forEach(progress => {
        progress.projectId = projectId;
        addBrandProgress(progress)
      })
    },
    updateProjectProgressList() {
      const projectId = this.form.projectId
      delBrandProgress(projectId).then(
        this.addProjectProgressList()
      )
    },
    getProjectProgressList() {

    },
    formartProjectProgress(row) {
      if (row <= 20) {
        return 'exception'
      } else if (row > 20 && row <= 50) {
        return 'warning'
      } else if (row > 50 && row <= 80) {
        return null
      } else {
        return 'success'
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const projectIds = row.projectId || this.ids;
      this.$modal.confirm('是否确认删除品牌项目编号为"' + projectIds + '"的数据项？').then(function () {
        return delBrandProject(projectIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/brandProject/export', {
        ...this.queryParams
      }, `brandProject_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/assets/styles/element-reset.scss";

table {
  /*边框*/
  /* border: 1px solid black; */
  text-align: center;
  border-collapse: collapse;
  /*设置背景颜色*/
  /* background-color: #bfa; */
}

.require_input {
  color: #f00;
  font-size: 20px;
  font-weight: bold;
  display: inline-block;
}

::v-deep .el-descriptions-item__label.is-bordered-label {
  color: #5a5757;
  background: rgba($color: #a9adb3, $alpha: 0.1);
  width: 150px;
  min-width: 150px;
}

::v-deep .el-descriptions .is-bordered .el-descriptions-item__cell {
  border: 1px solid #cdd0d3;
}
</style>